Storing Uploaded Files in a Database or in the File System with ASP.NET 2.0

Update 2010/08/10: I just posted an article featuring a new version of this application based on the Provider Model design pattern. You can find the article here.

A common requirement in web sites is handling client files that are uploaded through the browser. Whether these files come from a protected Admin section where content managers can upload files, or from a public section doesn't matter; you need a way to retrieve and store these files in your system somewhere so they are available for viewers.

Allowing a user to upload a file is easy; just drop a FileUpload control on your page and .NET will handle the rest for you. However, it's after the file gets uploaded to the server where things get interesting. One of the things you have to take into account is where you're going to store the uploaded file. Two common places are the hard drive of your server and a database. There has been a lot of debate on the Internet about the best way to store your files. Some say the file system is the only acceptable option, while others really like the database solution.

In this article I'll show you how to store files both ways. I'll discuss the pros and cons of each solution, and show you the code you need to save your uploaded files. As a sample application, I'll build a small web site that allows you to upload files and store them at a location that you determine. You can decide where the files are stored through a simple setting in the web.config file. Depending on this setting, files are either stored directly at the hard drive of your server or in a database. You can even change this setting at run-time without affecting existing files.

Introduction

UPDATE 2006/01/17: I added the VB version of the code to the Downloads section

Right now, the article and the code download are in C# only, but I am working on a Visual Basic version of the application as well. Send me a nice e-mail if you want me to hurry up...

I converted the code to Visual Basic .NET using DotNetTaxi's Code converter and then manually fixed a few remaining issues. I tested the application and everything seems to work fine. If you do find an issue, please let me know. The full VB code is available in the Downloads section at the end of this article.

Besides showing how to store files in the database and retrieve them again, this article also presents a little demo application that demonstrates the concepts from this article. Instead of performing all the code directly in the code behind of the ASPX pages, this application uses a number of separate classes that each perform a limited set of tasks. If you're not interested in the design of the application or the pros and cons of storing files in the database, you skip directly to the code that shows you how to save files in the database and retrieve them again.

Before we start looking at the application and it's code, it's a good idea to briefly look at the pros and cons of both solution. Since so many people have a strong favor for one of the two solutions, there must be interesting differences between the two. Let's look at storing the files in the file system first.

File System - Advantages

One of the main benefits of storing the file on disk is that it's very easy to do. Just call SaveAs on a FileUpload control and you're pretty much done.

Another advantage is that files on disk are easy to backup; you just copy the files to another location. This also makes it easier to do incremental backups; files that have already been backed up don't need to be copied again.

FileSystem - Disadvantages

Storing your files in the file system has a few disadvantages as well. Probably the most problematic issue is the loosely coupled nature of the files on disk. They have no strong relation with a record in the database. So, when you delete, say, a product from the database, you may end up with an orphaned product image. There is no direct way to do an INNER JOIN between the product table and your images folder to determine what orphaned files you have left. This means that a page developer is responsible for writing code that deletes the file from disk whenever the associated database records gets deleted.

Also, to store uploaded files on disk, your web server needs permissions to write to the file system. This is easy to come by when you run your own server, but may prove to be more problematic in an ISP scenario.

Database - Advantages

Of course some of the advantages of a database are the exact opposite of the disadvantages of saving them as physical files: since they are stored in the database, they're easy to relate to other records. They can be retrieved in JOIN style queries, and even be deleted automatically with cascading delete turned on. You also don't need additional permissions on the server; if you can write to the database, you can store files in it.

But another advantage of storing your files in a database is the fact that all data is contained in a single location. Make a backup of your database, and you have everything you need. That makes it a lot easier to move your data to another server; other than the database, you don't need to copy files, set up permissions and so on.

Database - Disadvantages

At the top of the list of disadvantages of storing your files in a database is probably performance. While I don't have any hard figures to support this, the "word is" that it's slow. How slow may depend on your situation, the type of files you have, the server, and so on.

Another downside is the lack of easy access to the files. When you store them on disk, it's easy to download them to your desktop machine and batch process them; for example, use an imaging program to scale or rotate all your images. When you use a database, you need to "materialize" them to disk first and upload them again afterwards.

A final problem with the database is backups. Whenever you make a full backup of your database, all the files are included, whether they have been changed or not. If you copy your backups to a different machine or network for safety reasons, this could be problematic as you need to move the entire backup file. With a file based solution, you can use diff programs that can determine which files have been changed since the last backup, and only download those.

Realizing that both methods have their pros and their cons, the question is: what to choose? Personally, I favor storing them on disk. The accessibility of the files on disk, combined with the simple coding model makes the disk solution a better one in many situations. However, I have also used the database solution at places where that made more sense. Bottom line is that you need to carefully examine your scenario and determine what works for you.

The solution I am presenting in this article shows you how to do both; with a simple option in the web site's config file, you can switch between a file based and a database solution.

Storing the Files

When you store the files on disk, things are pretty easy. The SaveAs method on the PostedFile does all the work for you, provided you set the right security settings. Storing them in a database isn't too hard either, but you need to be aware of a few things. First of all, you need to know what data type to use to store your files. With SQL Server 2000, you can use the image data type. Although its name suggests you can only use it to store image files, this is not true. You can store text files, Word documents, spread sheets or any other file type you have. With SQL Server 2005, you can use the new varbinary(max) data type. The sample application that comes with this article uses a SQL Server 2005 Express database and thus the varbinary(max) data type. If you want to use SQL Server 2000 instead, simply replace each occurrence of varbinary(max)with the image data type, including the FileData column in the Files table.

Additionally, you need to know the code to access the database to store and retrieve the files. You'll see a lot more of that right after I discussed the demo application and its feature set.

The Demo Application - A Simple File Manager

The demo application used in the article is a simple web site that allows you to upload, download and view files. With an optional switch in the web.config file, you can determine whether the files are stored in the database or on disk. The code for the entire application is available in the Download Files section at the end of the article.

The application contains four .cs files in the App_Code folder, a SQL Server 2005 Express database, four .ASPX files with code behind and a web.config file, all of them visible in Figure 1.

The Solution Explorer for the Demo Project
Figure 1 - The Solution Explorer for the Project

In this article, I'll show what each file is used for and what code it contains. I won't discuss each and every line of code in the application, but instead focus on the important concepts. You're encouraged to download the application so you can see the full source, and play around with it.

To keep the discussion focused, the design of the application is extremely simple. It features a page with a standard GridView that displays the files that have been upload:


Figure 2 - A GridView Showing the Uploaded Files

Each uploaded file always has a Download link to allow a user to download the file from the server. For files that can be viewed in the browser, there's also a View link. This works only for files like images, Word documents and text files in the demo application, but it's easy to extend this to other files, like Excel spreadsheets.

If you click the Add New File button, you can upload a new file which is then shown in the GridView in Figure 2.

The Demo Application - Class Design

Instead of doing all the code logic in the page's code behind, the application uses a class based design, where each class has a strong focus on a single task. Let's take a look at the class design for the application:


Figure 3 - The Class Diagram for the Sample Application

The class diagram in Figure 3 contains three classes and one enumeration. I'll discuss all four of them in the following section.

The File class

The File class represents an uploaded file and is used to store and retrieve uploaded files on disk and in a database. The database is used in both scenario's. Even when you decide to save the files on disk, some meta data of the file is still stored in the database. The File class has properties to store the ContentType of a file (like image/jpeg, application/msword etc), the date it was created (DateCreated), its unique ID in the database and the original name of the file when it was uploaded (OriginalName). It also contains a FileUrl which is used when files are stored on disk, and a FileData property which contains the actual file when it's retrieved from the database. The last property of the File class is ContainsFile, which indicates whether the file holds the bytes for the uploaded file in FileData, or that it contains a virtual path to the file on disk in FileUrl.

It also contains two constructors and two methods: one to get a file (from the database or from disk) and one to save the file. This Save method has two public overloads and one private version that performs the actual save operation.

The FileInfo class

The FileInfo class serves as a lightweight summary object for the file. A FileInfo object basically contains the meta data of the file, but without the actual file or virtual path to it. This is useful in scenarios where you want to display a list of files, as in Figure 2. In such a case, it doesn't make much sense to have each item in the GridView contain the actual file, as you aren't doing anything with it. By using a lightweight FileInfo object, you can save some overhead and speed up your application.

The AppConfiguration Class

If you're familiar with my latest book ASP.NET 2.0 Instant Results, you should be familiar with this class. It's a static class that's essentially a wrapper around some settings in the web.config. While you can certainly access the web.config file from code directly, I prefer to wrap them in a static class with static properties, so I have easy access to them and get Intelli Sense on them.

The ConnectionString property defines the connection string to the SQL Server database (a SQL Server 2005 Express database in the demo application), while UploadsFolder contains a virtual path to the folder where uploaded files are stored (for example: ~/Uploads)

The final property of this class is DataStoreType which determines the location where to store the files. The DataStoreType enumeration is discussed next.

The DataStoreType Enum

The DataStoreType enumeration contains two members: Database and FileSystem. When the application is configured to use Database, all files are stored in the SQL Server 2005 database, When FileSystem is specified, then the meta data is still stored in the database, while the actual files are saved to disk.

Uploading Files

OK, enough for the theory, let's look at some code.

When you click the Add New File button you see in Figure 2, you're taken to UploadFile.aspx. The markup of this page is extremely simple and only contains an <asp:FileUpload /> control and a Button. When you select a file and then click the Upload File button, the following code is executed:

protected void btnUpload_Click(object sender, EventArgs e)
{
  if (FileUpload1.HasFile)
  {
    string contentType = FileUpload1.PostedFile.ContentType;

    // Get the bytes from the uploaded file
    byte[] fileData = new byte[FileUpload1.PostedFile.InputStream.Length];
    FileUpload1.PostedFile.InputStream.Read(fileData, 0, fileData.Length);

    // Get the name without folder information from the uploaded file.
    string originalName = Path.GetFileName(FileUpload1.PostedFile.FileName);

    // Create a new instance of the File class based on the uploaded file.
    File myFile = new File(contentType, originalName, fileData);

    // Save the file, and tell the Save method what data store to use.
    switch (AppConfiguration.DataStoreType)
    {
      case DataStoreType.Database:
        myFile.Save();
        break;
      case DataStoreType.FileSystem:
        myFile.Save(Server.MapPath(Path.Combine(
        AppConfiguration.UploadsFolder, myFile.FileUrl)));
        break;
    }
    Response.Redirect("~/");
  }  
}  

(From: UploadFile.aspx.cs)

The code first checks if a file has been uploaded by looking at the HasFile property. If that's the case, its content type is derived from the ContentType property of the PostedFile.

Next, a byte array is created from the uploaded file. First, the array is dimensioned to the length of the uploaded file and then it's filled by calling Read on the InputStream of the PostedFile. At this stage, fileData contains the actual bytes of the file the user has uploaded.

Then the original name is retrieved. By default, PostedFile.FileName contains the full path and name of the file at the client's computer. Since we're only interested in the file's name (and extension) and not in the original path, Path.GetFileName is used to strip off the path.

Then a new File object is constructed with a constructor that accepts the content type, the file name and the bytes for the file. Inside this constructor, the parameters are stored in the class's backing variables, like this:

public File(string contentType, string originalName, byte[] fileData)
{
  this.id = Guid.NewGuid();
  this.contentType = contentType;
  this.fileData = fileData;
  this.originalName = originalName;

  string extension = Path.GetExtension(originalName);
  string fileName = this.Id.ToString() + extension;

  this.fileUrl = fileName;
}

(From: File.cs)

Notice how the constructor builds up the unique fileUrl for the file, by adding a Guid and the file's extension together. This way, each file ends up with a unique name so you don't have to worry about files being accidentally overwritten. Since the original name of the file is always stored in the database, it's easy to use that name again when the file is downloaded. You'll see how this works later.

Once the new File instance is ready, it's saved by calling Save(). There are two public overloads of the Save method; a parameterless version that saves the file in the database and an overloaded version that accepts the physical location of where the file must be saved. Notice that the correct overload is chosen based on the DataStoreType:

// Save the file, and tell the Save method what data store to use.
switch (AppConfiguration.DataStoreType)
{
  case DataStoreType.Database:
    myFile.Save();
    break;

  case DataStoreType.FileSystem:
    myFile.Save(Server.MapPath(Path.Combine(
          AppConfiguration.UploadsFolder, myFile.FileUrl)));
    break;
}

(From: UploadFile.aspx.cs)

Both of the two public versions of the Save method call another, private overload that accepts a DataStoreType and the physical location of the file. This version of the Save method is discussed next.

Saving the File

The Save method contains a lot of code, but most of it is pretty standard ADO.NET code:

private bool Save(DataStoreType dataStoreType, string filePath)
{
  using (SqlConnection mySqlConnection = new
          SqlConnection(AppConfiguration.ConnectionString))
  {
    // Set up the Command object
    SqlCommand myCommand = new SqlCommand(
          "sprocFilesInsertSingleItem", mySqlConnection);
    myCommand.CommandType = CommandType.StoredProcedure;

    // Set up the ID parameter
    SqlParameter prmId = new SqlParameter("@id",
        SqlDbType.UniqueIdentifier);

    prmId.Value = id;
    myCommand.Parameters.Add(prmId);

    // Set up the FileData parameter
    SqlParameter prmFileData = new SqlParameter("@fileData ",
          SqlDbType.VarBinary);
    // If we need to store the file in the database, 
    // pass in the actual file bytes.
    if (dataStoreType == DataStoreType.Database)
    {
      prmFileData.Value = fileData;
      prmFileData.Size = fileData.Length;
    }
    else
    {
      prmFileData.Value = DBNull.Value;
    }
    myCommand.Parameters.Add(prmFileData);

    // Set up the FileUrl parameter
    SqlParameter prmFileUrl = new SqlParameter("@fileUrl",
        SqlDbType.NVarChar, 255);
    // If we need to store the file on disk, save the fileUrl.
    if (dataStoreType == DataStoreType.FileSystem)
    {
      prmFileUrl.Value = fileUrl;
    }
    else
    {
      prmFileUrl.Value = DBNull.Value;
    }
    myCommand.Parameters.Add(prmFileUrl);

    // Set up the OriginalName parameter
    SqlParameter prmOriginalName = new SqlParameter("@originalName",
          SqlDbType.NVarChar, 50);
    prmOriginalName.Value = originalName;
    myCommand.Parameters.Add(prmOriginalName);

    // Set up the ContentType parameter
    SqlParameter prmContentType = new SqlParameter("@contentType",
          SqlDbType.NVarChar, 50);
    prmContentType.Value = contentType;
    myCommand.Parameters.Add(prmContentType);

    // Execute the command, and clean up.
    mySqlConnection.Open();
    bool result = myCommand.ExecuteNonQuery() > 0;
    mySqlConnection.Close();

    // Save the file to disk if necessary; shown later

    return result;
  }
} 

(From: File.cs)

This code creates a SqlConnection and a SqlCommand object and then creates a number of parameters. Most of them are pretty straight forward, but the fileUrl and fileData parameters need a bit more explanation (highlighted in the code above). When the DataStoreType passed in equals Database, it means the actual file is stored in the database. In that case, the fileData property is assigned to the value of the prmFileData parameter. The type of that parameter is SqlDbType.VarBinary, which corresponds to the data type of the column in the database. (When you're using SQL Server 2000, you should use SqlDbType.Image instead.) Since the file has already been converted to a byte array in the calling code, all you need to do here is assign the fileData variable to the parameter's Value property.

In the else clause (when the FileSystem option is used), DBNull.Value is passed instead, so null is stored in the database.

The FileUrl parameter takes the opposite approach and only passes its value when DataStoreType is FileSystem.

Finally, the Command object is executed against an open database connection and the result of the ExecuteNonQuery call is stored in a temporary variable.

Notice that when the FileSystem is used, the Save method also saves the file to disk:

// Database update is done; now store the file on disk if we need to.
if (dataStoreType == DataStoreType.FileSystem)
{
  const int myBufferSize = 1024;
  Stream myInputStream = new MemoryStream(fileData);
  Stream myOutputStream = System.IO.File.OpenWrite(filePath);
           	byte[] buffer = new Byte[myBufferSize];
  int numbytes;
  while ((numbytes = myInputStream.Read(buffer, 0, myBufferSize)) > 0)
  {
    myOutputStream.Write(buffer, 0, numbytes);
  }
  myInputStream.Close();
  myOutputStream.Close();
}    

(From: File.cs)

To save the file, the byte array is converted back to a Stream again, which is then written to disk using another Stream object. For the file name, this code uses the filePath parameter passed to the Save method.

As an alternative to this solution, you can decide to call the SaveAs method on the FileUpload control in the code behind of UploadFile.aspx. This is easier, as the SaveAs method takes care of it all; all you need to do is pass a file name. However, it also means you're spreading logic across your application. By encapsulating all the code into a single File class, your application becomes easier to maintain and extend.

As another alternative, you could pass the entire FileUpload control to the Save method, and have that method call its SaveAs method. Personally, I don't like that solution too much, as it ties the File class to a WebControl, which makes it harder to reuse it in other type of applications.

The stored procedure that is used in the Save method is really simple; it performs a simple INSERT operation in the File table:

CREATE PROCEDURE sprocFilesInsertSingleItem

  @id uniqueidentifier,
  @fileUrl nvarchar(255),
  @fileData varbinary (max),
  @originalName nvarchar(50),
  @contentType nvarchar(50)
  
AS
  
INSERT INTO Files
(
  Id,
  FileUrl,
  FileData,
  OriginalName,
  ContentType
)
VALUES
(
  @id,
  @FileUrl,
  @FileData,
  @originalName,
  @contentType
)

(From: sprocFilesInsertSingleItem)

Again, the varbinary(max) data type is used for the fileData parameter, to line up with the SqlParameter and the column for the file in the database as you saw earlier.

With the Save operation done, the next thing to look at is displaying files.

Displaying the Files

To display files in a web browser, there are two scenario's to consider: displaying lists of files, and displaying or downloading a single file. I'll look at the list first, followed by the single file.

Viewing a List of Files

The page Default.aspx, that displays a list of files that can be downloaded or viewed, contains a simple GridView with a few columns that display the file's unique Id, original name, content type and the date and time it was uploaded. It also contains two columns that allow you to download a file and - in certain circumstances - view the file in-line in the browser. In Figure 2 you can see that only some files have the View link enabled. Some code in the code behind looks at the content type of the file in each row, and enables the View link when the file can be viewed in-line in the browser. That's the case for images (jpg, gif for example) and other files that the browser can usually handle (Word files, Excel spreadsheets). Other files that can't be viewed directly, but need a separate application (Zip and Rar files for example) can only be downloaded. You'll see the code for this a little later.

The GridView gets its data from an ObjectDataSource control that is tied to the FileInfo class with its GetList method. You could opt to implement the GetList method in the File class and remove the entire FileInfo class. However, I have chosen to implement it like this for performance reasons. In most scenarios, when you display a list of files, you don't need the actual files; all you need is some meta data like the name and unique ID. By implementing a simple, and read-only class FileInfo, you get all the data you need without the overhead of retrieving all the files from the database.

Because all the work is done by the GetList method of the FileInfo class, the ObjectDataSource is very simple:

<asp:ObjectDataSource ID="odsFiles" runat="server" 
    SelectMethod="GetList" TypeName="FileInfo" />      

(From: Default.aspx)

When this control gets its data, it calls the static GetList method that returns a generics List of FileInfo objects:

public static List GetList()
{
  List<FileInfo> myList = null;

  using (SqlConnection mySqlConnection = new SqlConnection(
              AppConfiguration.ConnectionString))
  {
    SqlCommand myCommand = new SqlCommand("sprocFileInfoSelectList", 
              mySqlConnection);
    myCommand.CommandType = CommandType.StoredProcedure;

    mySqlConnection.Open();
    
    using (SqlDataReader myReader = myCommand.ExecuteReader())
    {
      if (myReader.HasRows)
      {
        myList = new List<FileInfo>();
        while (myReader.Read())
        {
          myList.Add(new FileInfo(myReader));
        }
      }
    }
    
    mySqlConnection.Close();
  }
  return myList;
}      

(From: FileInfo.cs)

Again, most of this code is pretty straight forward. A SqlCommand executes the stored procedure sprocFileInfoSelectList to get the data from the database. Each record retrieved from the database is transformed into a FileInfo object that is added to a generics List<FileInfo>. To make the code a bit more readable, the FileInfo class has a constructor that accepts a SqlDataReader. This way, you only need a single line of code in the while loop to create a FileInfo instance and add it to the list. The constructor that accepts the SqlDataReader looks like this:

public FileInfo(SqlDataReader myReader)
{
  id = myReader.GetGuid(myReader.GetOrdinal("Id"));
  dateCreated = myReader.GetDateTime(myReader.GetOrdinal("DateCreated"));
  originalName = myReader.GetString(myReader.GetOrdinal("OriginalName"));
  contentType = myReader.GetString(myReader.GetOrdinal("ContentType"));
}

(From: FileInfo.cs)

Each of the four fields of the FileInfo class are filled with a value from the SqlDataReader. Since all fields are required in the database, there's no need to check for null values.

At the end of the GetList method, the list with FileInfo objects is returned to the calling code where it's bound to the GridView. For each FileInfo object that is added to the GridView, it fires its RowDataBound event that is used to determine whether the View link should be enabled or not:

protected void GridView1_RowDataBound(object sender, 
            GridViewRowEventArgs e)
{
  switch (e.Row.RowType)
  {
    case DataControlRowType.DataRow:
      FileInfo myFileInfo = (FileInfo) e.Row.DataItem;
      switch (myFileInfo.ContentType.ToLower())
      {
        case "image/pjpeg":
        case "image/gif":
        case "application/msword":
        case "text/plain":
          // Do nothing. When the row contains a viewable type, 
          // we want the View link to be enabled.
          break;
      default:
        // Find the View link and disable it.
        HyperLink myLink = (HyperLink)e.Row.FindControl("lnkView");
        myLink.Enabled = false;
        break;
      }
    break;
  }
}   

(From: Default.aspx.cs)  

Whenever a DataRow is added, a FileInfo object is retrieved from the DataItem property of e.Row. The FileInfo's ContentType is then used to determine whether the file is viewable in the browser or not. In the example above, this is only done for .jpg, .gif, .doc and .txt files but you can easily add additional case statements to the switch block.

For all other files, the link is retrieved with the FindControl method of the row and then its Enabled property is set to false.

Downloading or Viewing a Single File

When you click the Download or View link, you're take to DownloadFile.aspx or ViewFile.aspx respectively. The code behind of these files are pretty similar, but there are a few interesting differences worth looking at.

Both pages start by getting a File object from the database by calling File.GetItem. This method is pretty straight forward, and uses the same principle as the FileInfo class by implementing a constructor that accepts a SqlDataReader object to fill the private fields:

public File(SqlDataReader myReader)
{
  id = myReader.GetGuid(myReader.GetOrdinal("Id"));
  dateCreated = myReader.GetDateTime(myReader.GetOrdinal("DateCreated"));
  originalName = myReader.GetString(myReader.GetOrdinal("OriginalName"));
  contentType = myReader.GetString(myReader.GetOrdinal("ContentType"));

  if (!myReader.IsDBNull(myReader.GetOrdinal("FileData")))
  {
    fileData = (byte[])myReader[myReader.GetOrdinal("FileData")];
    containsFile = true;
  }
  else
  {
    fileUrl = myReader.GetString(myReader.GetOrdinal("FileUrl"));
    containsFile = false;
  }
}     

(From: File.cs)  

The first four fields are retrieved directly from the reader. The code then checks if the column FileData has a value that isn't null. If that's the case, the value is casted to a byte array and assigned to the fileData field. Notice that containsFile is also set to true to indicate that the File instance contains the actual file bytes. The public ContainsFile property is used in the download and view pages to determine whether the File instance contains the actual file bytes, or that they should search for the files on the server's hard drive.

In the else clause, the fileUrl (with the virtual path to the file on disk, starting from the virtual Uploads folder) is set, and containsFile gets a value of false.

Once the File object is returned, DownloadFile.aspx sets Response.ContentType to application/x-unknown and appends an additional header that contains the original name of the file. Then it uses either the BinaryWrite or the WriteFile method of the Response object, based on the fact whether the File object contains the actual file data:

Response.ContentType = "application/x-unknown";
Response.AppendHeader("Content-Disposition", 
      "attachment; filename=\"" + myFile.OriginalName + "\"");
if (myFile.ContainsFile)
{
  Response.BinaryWrite(myFile.FileData);
}
else
{
  Response.WriteFile(Path.Combine(AppConfiguration.UploadsFolder, myFile.FileUrl));
}

(From: DownloadFile.aspx.cs)  

In both cases, this forces the browser to display a File Download dialog that allows the user to save the file to disk :

The File Download Dialog that Allows a User to Save the File to Disk
Figure 4 - The File Download Dialog

The ViewFile.aspx page takes a similar approach, but first sets the ContentType that it retrieves from the File instance. It then switches between BinaryWrite and Redirect to send the file to the browser where it's displayed in line:

Response.ContentType = myFile.ContentType;
if (myFile.ContainsFile)
{
  Response.BinaryWrite(myFile.FileData);
}
else
{
  Response.Redirect(Path.Combine(AppConfiguration.UploadsFolder, myFile.FileUrl));
}

(From: ViewFile.aspx.cs)  

With the code to download or view an uploaded file, we've come full circle. You can now upload files to the server and store them on disk or in a database depending on your own preferences or requirements. You can list the files in a GridView and offer your users a way to download or display them.

Summary

Storing your uploaded files in a SQL Server database can be very convenient. It allows you to easily relate the uploaded files to other records in the database. However, there are also some disadvantages that you need to be aware of. One is performance, while another is increased backup-time. Whether you should save your files on disk or in a database depends on your own preferences and requirements.

This article showed you how to upload your files and store them in a database or on disk depending on a simple configuration switch. When you store them in a database, you can use the Image or the varbinary(max)data type. When you store them on disk, you need to ensure that the account used by the web server has sufficient permissions to write to the Uploads folder.

At the end of the article I showed you the code to either download a file or view it directly in the browser. Viewing it in the browser is not possible for every type of file. For example, .zip files cannot be viewed directly so they can only be downloaded. The code in the code behind of Default.aspx determines whether the View link must be enabled based on the file's ContentType property.

References

Download Files


Where to Next?

Wonder where to go next? You can read existing comments below or you can post a comment yourself on this article .


Consider making a donation
Please consider making a donation using PayPal. Your donation helps me to pay the bills so I can keep running Imar.Spaanjaars.Com, providing fresh content as often as possible.



Feedback by Other Visitors of Imar.Spaanjaars.Com

On Thursday, January 11, 2007 1:33:57 PM Yogesh Rankawat said:
I want to upload file up to 100MB. and save this file to SQL Server database. but I got an error of Timeout or Server Application Unavailable Error in Internet Explorer using ASP .NET Web Site.

Please help to resolve this problem

Thanks  
On Thursday, January 11, 2007 1:54:02 PM Imar Spaanjaars said:
Hi Yogesh,

I haven't tried this yet, but you could try setting Server.ScriptTimeout = LargeNumber in the page.

Alternatively, you can set executionTimeout in the web.config that comes with this example.

Cheers,

Imar
On Saturday, January 13, 2007 1:23:25 PM okboy said:
Thanks a lot.
Actually i am your instance result book supporter also. So i quite familiar your writing code skill in the VB..
So can you do it in VB, bcos i not really understand C# this language.
On Saturday, January 13, 2007 6:32:58 PM Lorenzo said:
Hello :) Enjoy your article!  I was wondering how would be implemented, theoretically, a switch to change the datastore with a DropDownList for example in the Default.aspx ?  This would help me understand how to access the web.config properties.
On Sunday, January 14, 2007 8:07:27 PM Imar Spaanjaars said:
Hi okboy,

I am about to start working on a VB version of the application; will post an update here when I am ready.

Cheers,

Imar
On Sunday, January 14, 2007 9:17:16 PM Imar Spaanjaars said:
Hi Lorenzo,

You can do that with the following code:

Dim myConfig As System.Configuration.Configuration = _
WebConfigurationManager.OpenWebConfiguration("~/")

Dim myElement As KeyValueConfigurationElement = Nothing

myElement = myConfig.AppSettings.Settings("DataStoreType")
If myElement IsNot Nothing Then
  myElement.Value = "Database"
End If

myConfig.Save()

This code opens the config file for the current application, gets a reference to the AppSettings element and then overwrites the value for DataStoreType.

For this code to work you need an Imports statment for the System.Web.Configuration namespace (found in the System.Configuration assembly).

The chapter AppointmentBooking in my latest book ASP.NET 2.0 Instant Results has a lot more information about this.

Hope this helps,

Imar
On Wednesday, January 17, 2007 10:52:28 PM Imar Spaanjaars said:
Hi okboy and others interested in a VB version of the code,

The VB version of the application is now available in the Downloads section of this article.

Cheers,

Imar
On Friday, January 19, 2007 5:40:33 AM okboy said:
THANK YOU VERY MUCH..
I need this feature for my application....
On Monday, January 22, 2007 6:23:18 PM Greg Fibiger said:
Hi Imar;

I'm having one of the moments again ...where do set the configuration switch to point to a filesystem and not the database?
On Monday, January 22, 2007 7:23:52 PM Imar Spaanjaars said:
Hi Greg,

Quote from the article: "You can decide where the files are stored through a simple setting in the web.config file".

Look in that file under appSettings. I commented one option out and left the other one active.

Cheers,

Imar
On Thursday, February 01, 2007 3:02:26 PM Greg Fibiger said:
Thanks Imar for the information under appsettings
On Sunday, February 04, 2007 3:45:37 AM IMarvinTPA said:
Another reason for database storage over server storage.
Security.  I live in a fairly restricted environment where no files can be changed on the server except during releases.  It also prevents any hack files from finding their way onto the server itself.
I'm not the security guy, but it is why I have to do the database storage route.

IMarv
On Sunday, February 04, 2007 1:05:00 PM Lorenzo said:
Interesting point so I am asking what would happen then, I could introduce malicious code via an upload?  Is it possible to check for incoming file types and discard them at runtime?  How would be safer to store them in a db, no malicious code can run within the DB itself?
On Sunday, February 04, 2007 2:51:45 PM logic said:
I was asked this question, but I had no answers. The question is: How is this done?  If you look at the FIRST LINE below  UPDATE right BELOW INTRODUCTION on this article, you have the TEXT LINES CROSSED OUT.
What is the CSS syntax how do you achieve that?
Thanks,
logic
On Sunday, February 04, 2007 5:37:32 PM Imar Spaanjaars said:
Hi logic,

Did you look at the HTML source for this page? That's the easiest way to learn these kind things.

You can accomplish this with the HTML s tag: [s]Some Text[/s] (where you need to replace [] with normal HTML tag characters.)

Additionally, you can use the CSS text-decoration property:

.SomeClass
{
  text-decoration: line-through;
}

[p class="SomeClass"]Some text[/p]

Hope this helps,

Imar
On Sunday, February 04, 2007 10:27:16 PM Imar Spaanjaars said:
Hi IMarvinTPA,

Interesting point; thanks for adding that....

Lorenzo: you can still look at the extension and content type of the uploaded file.....

Imar
On Monday, February 05, 2007 5:10:47 AM SimonHong said:
good!
but , i noticed you store file in web subfold ,so  there has a security  issue, somebody may upload a aspx/aspx.cs file ,and run it in browser.
the solution is make this fold not a application fold , or ,in my project ,sotre in a fold that not under the web fold .
On Monday, February 05, 2007 6:46:02 AM Imar Spaanjaars said:
Hi SimonHong,

Yes, good suggestion. I'll see if I can update the article and make this point clearer early in the article.

Cheers,

Imar
On Monday, February 05, 2007 2:26:39 PM Haroun said:
Hello Imar--Thanks for this informative article. I purchased your Instant results book, and I am learning a lot from it.  I see the code is copywrited by wrox.  is there any restrictions for using it in commercial apps.

Cheers,

Haroun
On Monday, February 05, 2007 6:02:24 PM Steven Bey said:
An interesting article but i think this would have been better if you had implemented it using the Provider model. That way you could specify, in configuration, which provider to use. It is also a lot more flexible and extensible. For example, if you needed to change the type of database from SQL Server to MS Access or Oracle, you would simply create the appropriate Provider class and then change the configuration to use it.
On Monday, February 05, 2007 8:42:39 PM Imar Spaanjaars said:
Hi Steven,

I originally started this article as a little code snippet showing how to store files in the database. Then I decided to add an introduction about advantages and disadvantages of both methods. While I was discussing the file system solution, I decided to show the code for that as well.

Then I decided the next step was to create some classes that were easy to reuse in other applications.

I think the next natural step in this process is implementing the provider model. Great suggestion!
On Wednesday, February 07, 2007 5:04:30 PM Merrill Callaway said:
You left out one major advantage to storing files in a database: full text searching of file content. If you use MS SQL Server, you can perform queries against the uploaded file's content. Storing the file in a database is essential if the web application must be able to search document content; for example in a document management application, you could store meta-data about the document in the ordinary database fields and the document itself as an 'image' datatype (binary data) field in the database. The 'image' field could then be searched for strings in its content using SQL Server Full Text features.  
On Wednesday, February 07, 2007 6:46:06 PM Imar Spaanjaars said:
Hi Merrill,

Well, you can do that with Index Server for disk based files, can't you? That way, you can also search PDF docs, zip files and so on.

Granted, you may need to join the results with another query that queries the database, but IMO, it's not "essential" to store the files in a database as you can also search the disk based files......

Imar
On Thursday, February 08, 2007 9:01:34 PM Don Good said:
This file upload method is dependent upon the HTTP protocal and there are a couple items that should also be mentioned.

The first has to do with the reason behind the first comment inre the large file.  IIS handles incoming requests inproc and so there is a built-in failsafe to prevent a large request from using to much memory and causing performance issues.  A HTTP request embeds the file in the request body and is thus impacted by this failsafe.  By default IIS errors out if a request size exceeds 4megs.  You can change this using the maxRequestLength arguement from the system.web/httpRunTime node in any config file.  The following sets it to around 20megs.

    [httpRuntime maxRequestLength="20480"/]

Microsoft does not recommend setting this larger than 25 or so megs.

The second issue is that some browsers may still limit the size of files that can be uploaded through HTTP.  I know IE5 threw an error if you attempted to upload a file around 10megs; IE6 and IE7 appear to allow files of any size but I am not sure about Firefox, Safari or others.

And finally keep in mind dial-up users.  At 56k it still is around 10 minutes per meg (these users till exist).
On Friday, February 09, 2007 5:26:34 PM Rodney said:
hey all,
thanks for the article first of all, how could i modify the code so when you click view it opens in a different browser?

thanks,
rodchar
On Friday, February 09, 2007 5:52:13 PM Imar Spaanjaars said:
Hi Don,

Thank you for your contribution I am sure the httpRuntime setting comes in handy for readers of this article.

Rodney: you can do this by adding a Target attribute to the HyperLink that allows you to view the item:

asp:HyperLink ID="lnkView" Target="_blank" runat="server"

Cheers,

Imar
On Monday, February 12, 2007 7:45:13 PM Chris said:
I'm using Java on WebSphere app server and also had preferred to store the uploaded files on a file system for all the same reasons Imar stated.  However, our QA and production environment is clustered, so a central file share would be necessary to make this work.  Apparently, a lot of AIX/unix shops do not even support network file shares (including the one I'm working for) - so I have to change the code to work with a Database instead!
On Tuesday, February 13, 2007 12:01:31 AM Tanya Goette said:
Maybe someone can point me to a way to solve a similiar issue.  I am using ASP.Net 2.0 with an Access database.  I have an Excel spreadsheet.  I need to upload the Excel spreadsheet (that's the easy part) and compare it to the Access database table records.  I want to ignore excess columns in the spreadsheet and update the records in the database that have changed information and add any new records that exist in the spreadsheet but not the database. Any suggestions?
On Tuesday, February 13, 2007 7:39:21 PM Imar Spaanjaars said:
Hi Tanya,

I am afraid this is not as similar as you may think.

If you want to to this with pure code, you need to open a connection to the Excel file, read the records and compare them with the Access database. Search Google for import excel c# and you'll get some useful results.

For a more 1 on 1 import, you could also take a look at SQL Server's DTS. It allows you to import data from Excel into Access, but obviously it requires access to SQL Server somehow.

Cheers,

Imar
On Wednesday, February 14, 2007 3:37:23 PM Chris Hynes said:
You may want to consider using an upload manager component, like my SlickUpload component (http://krystalware.com). This resolves a lot of the scalability issues by streaming directly to disk or database instead of loading the file to memory. It also allows you to provide rich progress feedback to a user in real time during an upload.
On Friday, February 16, 2007 1:52:57 PM Rodney said:
Hi Imar,
how could i implement a delete procedure for the zip files that get left on the server?

thanks,
rodchar
On Friday, February 16, 2007 9:42:12 PM Imar Spaanjaars said:
Hi Rodney,

What do you mean with Zip files left on the server? If you want to implement delete logic, you can either fire a SQL DELETE statement when you're using the database, or use System.IO.File.Delete to delete a physical file.

In both cases, you can use the code from the Download or View page to determine what fiie to delete.

Cheers,

Imar
On Thursday, February 22, 2007 2:49:44 AM Shailesh Mark said:
Imar, hello again -- we talked a couple of years ago in the Wrox forums.

This is an excellent demonstration. I am however having trouble downloading file either from the database or the file system. Adobe pdf says "the file is damaged and could not be repaired". I can double click on the file in the file folder and it opens without any problem. However, the same file would not open when downloaded through the code. Any idea? Thanks.
On Monday, February 26, 2007 4:48:46 PM Theresa said:
Great Article.

Is there a way to write the contents of the file saved in a database without using "Response".  I'm wondering if it is possible to write out the content of the file into a DIV tag so I can control its location on the page.
On Monday, February 26, 2007 6:49:26 PM Imar Spaanjaars said:
Hi Theresa,

Yeah, you can do that by getting a string out of the FileData through a UTF7 object, like this:

System.Text.UTF7Encoding myUtf = new System.Text.UTF7Encoding();
string result = myUtf.GetString(myFile.FileData);
myLabel.Text = result;

The last line sets the Text property of a Label in a page, but once you have the data in the string result, you can do with it whatever you want.

This works well with text based files only, of course....

Cheers,

Imar
On Monday, February 26, 2007 7:22:19 PM Theresa said:
Hi Imar,

I actually need to do this for a PDF file.  I'm guessing there's nothing built in that will work for that?  Thanks for the info. though, I'm sure it will be useful later on.
On Monday, February 26, 2007 8:53:30 PM Imar Spaanjaars said:
Hi Theresa,

It's not about being built in or not, it's about how browsers work. You can't display a PDF document together with HTML in the same window / document.

However, you can use the file based solution (ViewFile.aspx) together with an iframe tag. Simple use an HTML iframe with its src attribute set to the file, like ViewFile.aspx?Id=1234 and the PDF will display in the iframe.

Hope this helps,

Imar
On Wednesday, February 28, 2007 9:12:26 PM Jay said:
Great Article!  I am interested in modifying your VB code slightly so that I can filter the GetList() function base on a Request.QueryString ID field.    However, I keep receiving an error Procedure or Function 'sprocFileInfoSelectList' expects parameter '@Id', which was not supplied.   Obviously, I am doing something wrong.  Do you possibly have an example on how to do this from a Request.Querystring/

Thanks,
Jay
On Wednesday, February 28, 2007 9:52:37 PM Imar Spaanjaars said:
Hi Jay,

I think the best thing to do is to post this on a forum like http://p2p.wrox.com and then send me a link.

That way, it's much easier to post some code and describe your problem in more detail. If you do post there, don't assume others have read this article, so please post all relevant code.

Cheers,

Imar
On Saturday, March 03, 2007 12:28:03 AM Ki_Ki said:
Hi Imar, very nice article.
I have a problem with the hyperlink column.
I am actually populating the gridView diffently: I am using DirectoryInfo class. It allows me to go to a certain folder and retreive all files. It works fine but my Hyperlink button does not work. I have DataNavigateUrlFormatString="~/downloadPDF.aspx?fullname={0}"
where downloadPDF.aspx has code that should get the file name from  Request.QueryString.Item(0).ToString
but for some reason the hyperlink is not hightlighted, not blue, and not clickable. I hope I was clear. Do you know what the problem might be?
Thank you.
On Saturday, March 03, 2007 10:55:10 AM Imar Spaanjaars said:
Hi Ki_Ki,

Hard to tell what's going on without seeing the rest of your code.

Can you take this to http://p2p.wrox.com and post the full code? That way, it'll be easier to see why this doesn't work.

Imar
On Tuesday, March 06, 2007 6:15:15 PM briiiin said:
Hi Imar,
how about letting a user only upload one image to their profile? so when they want to upload a new image the older is deleted from the system?
On Tuesday, March 06, 2007 9:20:20 PM Imar Spaanjaars said:
Hi briiiin,

Once you've defined what exactly a "user" is, you can take a unique property of the user and use that to save the file. For example, when using .NET Membership, you can use the ProviderUserKey property of the Membership user. E.g.:

fileName = Membership.GetUser().ProviderUserKey.ToString() + ".jpg";

Then you use fileName to save the image.

Hope this helps,

Imar
On Monday, March 12, 2007 4:35:11 AM briiin said:
Hi, Imar,
Brilliant. Thanks alot.
On Thursday, March 15, 2007 1:02:45 PM Sampath said:
Hi,
It is nice article,
I have worked with your article,
I have inserted some more fileds in the table,
I have field called jobcode in the database,
and i inserted a dropdownlist in the form based on selection change i try to change the content of gridview but it shows some error can u help me in this task please
Thank u
On Thursday, March 15, 2007 1:45:24 PM Imar Spaanjaars said:
Hi Sampath,

Hard to tell what's going on without looking at your code.

Can you post your code and a detailed explanation on a forum like http://p2p.wrox.com instead?

Imar
On Thursday, March 15, 2007 3:13:27 PM Sampath said:
hi,
Ok
I will send the Code to You
The Error occurs in FileInfo class
when i am trying to filter the items displayed in the Data Grid
the error occurs
On Thursday, March 15, 2007 3:25:34 PM Imar Spaanjaars said:
Hi Sampath,

You didn't read my message right. I didn't ask you to send me the code, I asked you to post it in a community like p2p.wrox.com so others can look at it as well.

Imar
On Thursday, March 29, 2007 6:04:05 PM David Country said:
U da man,

Holla at ur boyee
On Tuesday, May 08, 2007 4:26:11 PM azhari Gasmalla said:
Hi, Dear.
Please, tell me how can i setup the code in my computer.
I'm beginner.
Thanks.
On Tuesday, May 08, 2007 4:30:59 PM Imar Spaanjaars said:
Hi azhari,

Do you have Visual Web Developer 2005? If so, simply unzip the sample application and choose File | Open Web Site in VWD.

Otherwise, may I suggest you get a beginner's book on Visual Web Developer / ASP.NET 2.0?

Imar
On Tuesday, May 08, 2007 9:05:36 PM Stephen said:
I am trying to download the file (I am using a file sysetm folder to store the document, as opposed to the DB), and am having difficulty getting the file to download.  Any help would be appreciated.
On Tuesday, May 08, 2007 9:11:06 PM Imar Spaanjaars said:
Hi Stephen,

As Ken used to say: the error is on line 5.... ;-)

Bottom line: impossible to tell for me without seeing your code, error message and problem description.

May I recommend you post this on http://p2p.wrox.com and provide lots more details and your code?

Imar
On Wednesday, May 09, 2007 10:35:59 PM Jamie McShan said:
This is Great Stuff... I got it working fine with your DB, then I changed it to my own SQL Server db. In doing it, there is no varbinary with a MAX setting length. So I changed it to an Image type. This works fine with smaller files, but it seem like if the file is over say 300K or so, it bombs. Again works fine with small images and text files. But an Excel file at 300K says.  

"String or binary data would be truncated.
The statement has been terminated. "

In my understanding the Image type should allow for huge files.

Thanks for you help.
Great Stuff!

Jamie
On Thursday, May 10, 2007 10:18:34 PM Imar Spaanjaars said:
Hi there,

Are you sure you correctly updated all references to the Image column, including the stored procedure?

Imar
On Saturday, May 12, 2007 11:53:36 AM Imar Spaanjaars said:
Hi Jamie,

BTW: are you sure the error is caused by the Image column, and not by the file name or content type columns? I just uploaded a 20MB file into a SQL Server 2000 database and it worked fine.

Cheers,

Imar
On Monday, May 14, 2007 10:40:06 AM Todd said:
Hi Imar,

       Great article! I was just wondering if it was possible to store information into an sql database and also have the capabilities to click "view" and be able to see these files. I've tried it and the program looks for a URL which is stored as a null in the DB. Is there some way around this?
On Monday, May 14, 2007 10:52:03 AM Imar Spaanjaars said:
Hi Todd,

It shouldn't behave like that in the original source:

if (myFile.ContainsFile)
{
  Response.BinaryWrite(myFile.FileData);
}
else
{
  Response.Redirect(Path.Combine(AppConfiguration.UploadsFolder, myFile.FileUrl));
}

As you can see, when ContainsFile is true, the myFile opbject contains the file BLOB from the database, which is then streamed to the browser.

Cheers,

Imar
On Monday, May 14, 2007 1:59:56 PM Jamie McShan said:
Imar,

Thanks for the response. I did verify that all references of VARBINARYwere changed to IMAGE. I have tested uploading a small .jpg file and a large .jpg file. The small one works fine, the larger one, over 50k doesn't load. So I wouldn't think that it was the content type. Any other suggestions to try?

So you where able to convert your code to an IMAGE field?

This is what I get.

Exception Details: System.Data.SqlClient.SqlException: String or binary data would be truncated.
The statement has been terminated.

Source Error:

Line 228:      // Execute the command, and clean up.
Line 229:      mySqlConnection.Open();
Line 230:      bool result = myCommand.ExecuteNonQuery() > 0;
Line 231:      mySqlConnection.Close();
Line 232:


Thanks
Jamie
On Monday, May 14, 2007 8:45:17 PM Imar Spaanjaars said:
Hi Jamie,

Sorry, no, I am out of ideas. Like I said, it works fine for me on SQL 2000, with the Image type, so it's hard to suggest something....

Just make sure you converted all your code correctly to an Image type, including all procedures.

Are you using SQL 2000?

Imar
On Wednesday, May 16, 2007 4:38:40 AM omprakash bhoi said:
hi imar,
I have dwnlded ur demo application but in trying to run it , i got the error


Error 1 It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS. D:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WorkingWithFiles\WorkingWithFiles\Web.config 59


Can u figure out the problem?
On Wednesday, May 16, 2007 6:15:39 AM Imar Spaanjaars said:
Hi omprakash,

You're not opening it as a root application. In Visual Web Developer, make sure you open the folder WorkingWithFiles as the root of the site, and make sure there are no other web sites above this project in the folder structure.

In IIS: make sure that WorkingWithFiles is the root folder of an IIS web, and not a subfolder of your localhost. E.g. make sure you browse to http://localhost and not to http://localhost/WorkingWithFiles

If that doesn't help, search for the exact error message. This question has been answered 10,000 times on Google.... ;-)

Imar
On Saturday, May 19, 2007 4:42:43 AM naresh said:
Hi everyBody.... iam new to dotnet ...
Ive downloaded this application , but its not running... iam sure that the code will need some changes on system n data base connections ...
i donno wer to change n
Am getting this error ..........

Error 1 It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS. C:\naresh\naresh proj\WorkingWithFiles\WorkingWithFiles\Web.config 59
On Saturday, May 19, 2007 7:44:08 AM Imar Spaanjaars said:
Hi naresh,

Please read my reply to omprakash, just one message above yours as he had the same problem. You're not browsing to the site correctly.

Imar
On Sunday, May 20, 2007 5:25:52 PM Azhari said:
Dear,
how can change the source code to display specific rows depdending on receiver field that i added to the database?
using VB.
with best regards
On Sunday, May 20, 2007 7:49:51 PM Imar Spaanjaars said:
Hi Azhari,

Sorry, I don't understand what you're talking about...

Imar
On Monday, May 21, 2007 7:24:07 AM azhari said:
Dear,
I added a new field to the database, the field title is receiverN. so, when the user open default page, he only see files that are related to him.
I ask now about how can I change the source code of deault page and others to enable user to do that.
thanks.
On Monday, May 21, 2007 7:29:24 AM Imar Spaanjaars said:
Hi azhari,

If I understand you correctly, you can change the methods that get files and file lists and have it accept a userId, with the same type as receiverN.

Then forward this field to the stored procedure and use it in a WHERE clause to limit the list.

Cheers,

Imar
On Wednesday, May 30, 2007 11:24:37 AM kamal said:
Getting error----

Invalid object name 'Files'.



System.Data.SqlClient.SqlException was unhandled by user code
  Class=16
  ErrorCode=-2146232060
  LineNumber=11
  Message="Invalid object name 'Files'."
  Number=208
  Procedure="sprocFilesInsertSingleItem"
  Server="200.1.1.102"
  Source=".Net SqlClient Data Provider"
  State=1
  StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at File.Save(DataStoreType dataStoreType, String filePath) in C:\Documents and Settings\kvohra\Desktop\WorkingWithFilesVB\WorkingWithFilesVB\App_Code\File.vb:line 177
       at File.Save() in C:\Documents and Settings\kvohra\Desktop\WorkingWithFilesVB\WorkingWithFilesVB\App_Code\File.vb:line 129
       at UploadFile.btnUpload_Click(Object sender, EventArgs e) in C:\Documents and Settings\kvohra\Desktop\WorkingWithFilesVB\WorkingWithFilesVB\UploadFile.aspx.vb:line 17
       at System.EventHandler.Invoke(Object sender, EventArgs e)
       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
On Wednesday, May 30, 2007 11:37:54 AM Imar Spaanjaars said:
Hi kamal,

Please don't use this site as your on-line debugger. A quick search for the error message (Invalid object name) and Number (208) on Google should give you some useful results to fix this.

Imar
On Wednesday, May 30, 2007 2:23:44 PM azhari said:
Hi Imar.
I converted ID value from gridview using this code
Dim myGuid As Guid=New (myGridView.cells(0).Text)
then, I pass myGuid to function that has parameter of type Guid.
I receive this error:
System.FormatException: Input string was not in a correct format.
I seek for your help.
Thanks.
On Wednesday, May 30, 2007 2:32:42 PM Imar Spaanjaars said:
Hi azhari,

How is this related to this article?

Imar
On Wednesday, May 30, 2007 2:39:33 PM azhari said:
it's enable useres to delete files from aspx page! for example.
Dim myGuid As Guid=New (GridView1.cells(0).Text)
result.Text=DeleteFile(myGuid)
On Wednesday, May 30, 2007 2:48:25 PM Imar Spaanjaars said:
Hi azhari,

Right, I understand. But this is not part of the original code, is it? I mean, it's difficult for me to help you if I don't know on what code exactly this is basd.

Try posting it on a forum like p2p.wrox.com. If you do so, be sure to post your relevant code so people can see what it's about...

Imar
On Wednesday, May 30, 2007 4:22:01 PM Imar Spaanjaars said:
BTW: you may want to change this:

Dim myGuid As Guid=New (GridView1.cells(0).Text)

to this:

Dim myGuid As Guid = New Guid (GridView1.cells(0).Text)

and see if that helps.

Imar
On Thursday, May 31, 2007 2:14:07 PM azhari said:
I added two fields to Files Table of type nvarchar(30). one for senderName and other for recieverName.
the problem occur when I uploaded files; it uploaded two copies for each file that i uploaded.
Have you any comments?
thanks.
On Sunday, June 03, 2007 2:36:47 PM Dane said:
Hi, the codes were brilliant and I managed to even upload video files using it. The thing that I'm trying to do next is to View the uploaded videos using a ASPNetVideo adapter which I downloaded to Visual Studio 2005. I'm having troubles trying to bind the uploaded videos and redirect them to the video stream. The only thing it does is enable users to download the video file. Please advise. Thanks
On Sunday, June 03, 2007 8:33:06 PM Imar Spaanjaars said:
Hi azhari,

I can't imagine that adding two fields results in the file being uploaded twice, so I would look elsewhere if I were you.

Is it possible you're handling a Button's click twice?

Imar
On Sunday, June 03, 2007 8:38:53 PM Imar Spaanjaars said:
Hi Dane,

This is a bit too off topic for me to answer this here; I sugest you post this on one of the ASP.NET forums or on p2p.wrox.com

Cheers,

Imar
On Sunday, June 10, 2007 9:38:33 PM Maryam said:
Hello,
ehe code was greate I learnt alot of things from that I need some help regarding Databse I want to use the code in my portal so I need to move the table to the Portal databse ,as I create a new database table called Files and store 3 stored procedures I think everything should be finish but after I run my program after press "UploadFile"i get this error:
"Cannot insert the value NULL into column 'DateCreated', table 'C:\DOCUMENTS AND SETTINGS\MARYAM S\DESKTOP\TESTWORKINGWITH\APP_DATA\DATABASE.MDF.dbo.Files'; column does not allow nulls. INSERT fails.
The statement has been terminated. "
Can you please help me with the problem?
Thanks in advance.
On Monday, June 11, 2007 5:46:08 AM Imar Spaanjaars said:
Hi Maryam,

The column DateCreated has a default value of GetDate(). So, whenver you insert a new record, the current date and time is automatically inserted in that column.

Apparently, you forgot to provide this value when creating the DateCreated column.

Cheers,

Imar
On Monday, June 11, 2007 9:31:33 AM Maryam said:
Thanks Imar,
It was greate help from you.
Sincerely,
Maryam
On Friday, June 15, 2007 1:20:34 AM JianWei said:
Hi Imar.

This is indeed a good code! I referenced from it and it helped me alot. But however, I faced some problem, and seek your help on it.

First of all, I tried to do a similar database, but when I entered the "[Binary data]", errors occured. I didnt know what's the problem, so i didnt persist and i used the one you created.

Secondly, I did not want the id to be displayed on the gridview as it seems untidy so I tried deleting everything regarding "id", and even put OriginalName as the primary key. However, there are errors such as "invalid id" and I do not know what is the problem.

"System.Data.SqlClient.Exception: Invalid Column Name "id"" -- is the error. But from what I've seen I have already deleted all the things pertaining to id. I will appreciate if you can give me advise on this. Thanks
On Friday, June 15, 2007 1:27:53 AM JianWei said:
sorry that I forgot to add in the error arising.

The code that contains the error is:

using (SqlDataReader myReader = myCommand.ExecuteReader())
On Friday, June 15, 2007 5:26:19 AM Imar Spaanjaars said:
Hi JianWei,

You cannot just delete the primary key and expect things to work. OriginalName is not a primary key as many people could potentially upload a file with the same name. So, you need a primary in order to uniquely identify the rows in the GridView.

Why would you want to delete the Id column? If you don't want to display it in the GridView, simply set the Visible property of the Grid to False.

The error you get seems to suggest that the stored procedure still references the Id column.

Cheers,

Imar
On Thursday, June 21, 2007 9:26:54 AM kapil sharma said:
thanks yarr that is great detail fo uploading files.
On Thursday, July 05, 2007 11:47:56 AM Simon Westwood said:
I am looking for some code that will guide me through the process of uploading an image to sql 2005 express.  I have a table [ID,int],[Description,nvarchar(50)],[Image,image].

I am using VWD 2005 vb.net and need some serious help.

Regards
On Thursday, July 05, 2007 2:17:52 PM Imar Spaanjaars said:
Hi Simon,

Maybe you missed somehting in this article??? It *is* about uploading files to SQL Server 2005 Express.

Imar
On Thursday, July 05, 2007 2:35:25 PM Simon Westwood said:
I KNOW it IS about upload to sql 2005 express I need the code in vb.net no c#

Regards
On Thursday, July 05, 2007 2:50:55 PM Imar Spaanjaars said:
Hi Simon,

Please read the intro of the article again. There *is* VB code available. You just overlooked it.

Imar
On Thursday, July 05, 2007 2:56:15 PM Simon Westwood said:
Hi Imar,

My apologies,  They don't call me Mr McGoo for nothing do they Ha Ha.

Thanks again
On Wednesday, July 25, 2007 6:15:17 AM srinath reddy.M said:
it's too000000 good
On Wednesday, August 01, 2007 3:08:50 PM Reginaldo Pereira said:
Hi Dear,

The process that uploaded/downloaded of files is correct in my WebSite, but I have problem with big files (5MB), because the data type sql server (varbinary) not accept this length of file.

Please, Somebody can help me.

Thank you

Reginaldo Pereira
On Wednesday, August 01, 2007 9:29:22 PM Imar Spaanjaars said:
Hi Reginaldo,

Are you sure it's not something else, like IIS settings maybe?

varbinary(max) in SQL 2005 supports up to 2 GB....

Imar
On Friday, September 07, 2007 11:13:41 AM mbomas said:
hi,please help by providing this upload code in a 3 tier format,with all the sql statements in the BLL ,and how it will be called to the UI.i have tried to change it but i get s omany errors e.g Insertfiles @FileData paramenter expects a value witch wasnot supplied?? would really appreciate your help
On Friday, September 07, 2007 12:07:24 PM Imar Spaanjaars said:
Hi mbomas,

Sorry, I won't rewrite the application or article in a 3 layer format. This article is used to demonstrate upload concepts. My article series about n-layer design shows you how to design multi layer applications.

http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=416

It's up to you, the developer, to learn from this and combine the concepts. For me as an author, there wouldn't be much to gain from combining this, as it would be a simple iteration of what I have already written in these articles.

Obvously, it would make *your* life  as an individual implementing developer a lot easier, but I hope you understand that that is not my nr 1 priority.... ;-)

Cheers,

Imar
On Friday, September 07, 2007 12:42:31 PM rodchar said:
try changing your web.config file with the following:

   [httpRuntime maxRequestLength="25600"/]
[/system.web]
[/configuration]

the preceding limits file size to less than 25.6 MB.

hth,
rod.
On Monday, September 10, 2007 8:19:45 PM RIcky Moua said:
I ran your script.  I noticed I can upload files as large as 69megs.

It went to a "page cannot display" when I try to upload a 329megs.

Is there a way to put a limt say 30 megs.  If a person tries to upload
file larger then 30megs will get an error message telling that they exceed the upload size of 30megs.

Thanks.
On Monday, September 10, 2007 8:36:48 PM Imar Spaanjaars said:
Hi RIcky,

Not without a client side solution like Active X and before uploading the file. You can set the maxRequestLength limit, but an error will only be thrown if you have uploaded as many data as maxRequestLength permits. It won't be able to see the size of the file before you have sent it to the server.

Imar
On Monday, September 10, 2007 9:41:37 PM Ricky Moua said:
What about the "ContentLength"?  This supposedly will give
the size of the uploaded file in bytes.

Can we use this and say if this "ContentLength" is larger than 3megs then tell the user that he's exceeded the limit of 3megs instead of getting a "Page not displayed" which is so unfriendly.

Thanks.
On Monday, September 10, 2007 9:55:38 PM Imar Spaanjaars said:
Hi Ricky,

I don't think so. The ContentLength is available only in your own code after a successful upload. The error due to too large files occurs before your custom code fires.

Imar
On Monday, September 10, 2007 10:17:22 PM Ricky Moua said:
If that is the case, can we at least dispaly a page that is more friendly than the "page cannot be displayed" to the user.

I would like to at least tell the user that he's trying to upload a file that
exceeds the ASP.NET 4meg limit.

Thanks.
On Monday, September 10, 2007 10:23:14 PM Imar Spaanjaars said:
I am not 100% sure. I don't think that the request ever makes it into .NET's custom error handling. You could try it though.

You can also try changing the error (500) page in IIS directly and see if that helps.

Other than that, I am out of ideas.

Imar
On Friday, September 14, 2007 9:02:18 AM vipn said:
will u please guide me about how the upload of resume in various job site works in c# and Sql

plllzzzz
On Friday, September 14, 2007 9:57:51 AM Imar Spaanjaars said:
Hi vipn,

Heuh? Isn't this what this article is all about?

Imar
On Monday, September 24, 2007 5:41:52 PM Akbar said:
Hello,
Thanks for your great application,I want to expand the program so that save the files in the diffrent folders to categorize them in order,can you please help me in that?

and also I want to put a delete functinality!can you please help me with that also?
On Monday, September 24, 2007 6:17:31 PM Imar Spaanjaars said:
Hi Akbar,

You can use this application as the basis and use various methods in the System.IO.Directory class to create the actual folder structure.

Cheers,

Imar
On Tuesday, October 02, 2007 11:16:31 AM khanyisile said:
hi imar,have tried the upload example in 3tier,but need some advice........when uploading the the doc is stored in a file in the soluton explorer and in the database only the doc extension is stored,is it now posible to download? help!!
On Tuesday, October 02, 2007 11:22:01 AM Imar Spaanjaars said:
Hi khanyisile,

I am not sure what you're asking, or what the problem is.

Can you please post this on a forum like http://p2p.wrox.com? And if you do post there, please be as specific as you can and provide *lots* more detail.

Cheers,

Imar
On Sunday, October 14, 2007 6:16:15 PM joe said:
hi,
(this is regarding quickdoc=414)

I was wondering if you had any suggestions on how to display the files according to an additional criteria: the contents of a label.text.

I think I would need to accomplish two things: 1. add a column in the database that will capture the label.text from a label on the upload page so that every uploaded file is uploaded with an associated item for label.text. 2. add a sql parameter that only displays files according to the entry in the same label.text from the new db column.

Basically I am planning on capturing the email of the logged in user in a hidden label, so I can associate any uploaded files with that user. Then, when a user returns they would only see the files that they had uploaded instead of all files.

I realize you proabably don't have the time to walk through this in detail, I was just wondering if there was an easy solution or if you could put me on the right track. (I'm very new to all of this)
Any insight would be greatly appreciated.
Many thanks
-Joe
On Monday, October 15, 2007 5:55:18 PM Imar Spaanjaars said:
Hi joe,

Why would you need to store the name in a Label? Why not retrieve it from the currently logged on user directly?

Then give the Save method an overload that accepts the user's name, or even better, give the File class a PostedBy property.

You also need to give the GetList method a parameter that accepts the user name, so it can filter the Files for the current user only.

Hope this helps,

Imar
On Thursday, October 25, 2007 9:19:46 PM Joe said:
Imar,
thanks for the reply. Do know of any good resources that can walk me through how to do what you suggested? I've been combing every forum and message board for the last few weeks trying to solve this puzzle, but I don't understand the terminology terribly well.

Or is there a simple way to use the asp_username.name property from the automatic membership provider thing to accomplish this task? (I understand this part a little bit) Basically, your application provides the exact upload/download functionality I'm looking for- I just want to sort by the logged in user. I'm using the email that members login with as the "username", hence the part about the label control (I figured out how to set the Label.text = context.user.identity.name, so I hoped that i could do a SELECT WHERE email = label1.text or something like that)

I don't know.. any help is greatly appreciated.
thanks again,

-Joe
On Thursday, October 25, 2007 9:30:13 PM Imar Spaanjaars said:
If you can do this:

SELECT WHERE email = label1.text

Why can't you do this?

SELECT WHERE email = Context.User.Identity.Name

Imar
On Thursday, October 25, 2007 10:23:12 PM joe said:
not sure.. I got the WHERE email = label1.text bit to work with a different database using a sql data source, a gridview, and a code behind file. (different application)
i'm thinking it doesn't work because the files app uses stored procedures and an object data source? I tried to reference the label, but since it was in a stored procedure and not a page code-behind it didnt recognize it as anything. (red underline) Is there a way to reference a control on a separate aspx page via stored procedure? not sure f that would work either though...

(Sorry if this posts twice, i think i messed up the first try somehow)

thanks again
On Thursday, October 25, 2007 10:33:51 PM Imar Spaanjaars said:
You may have your logic and layering mixed up a little. You don't want to (nor can you) refer to a label from a stored procedure. Also, you don't want to (although you could) refer to a Label from code in a class called by an ODS.

Why not pass the user's name from the UI into the business object's method and process it there. You can use an additional parameter in the <Parameters> collection of the ODS for the user's name.

May I suggest you post this on p2p.wrox.com? It's much easier to post code there, and there are many others that can help you with this.

If you do post there, please post the relevant code and a detailed error / problem description....

Imar
On Tuesday, November 13, 2007 4:06:43 AM Robert said:
Hey There...
I trying to add a new column Artists ...but receiveing error


System.IndexOutOfRangeException: Artists

Source File: G:\SwingSet Group_inc\App_Code\FileInfo.vb    Line: 101

Line 101:    _artists = myReader.GetString(myReader.GetOrdinal("Artists"))


does this line need to say something dofferent?

On Tuesday, November 13, 2007 8:20:10 AM Imar Spaanjaars said:
Hi Robert,

Sounds like you forgot to query the column Artists in your stored pocedure.

Cheers,

Imar
On Wednesday, January 16, 2008 12:09:15 PM Brian said:
that it very powerful code and I like to say guys thanks a lot for every effort u have done so far especially does explanation and every single code you have been created. Another Major Issue is for Uploading that files to the database
On Monday, February 25, 2008 11:53:59 AM bharathi said:
hi,
I tried this code but i got the error "object reference not set to an instance of an object" how to overcome this error
On Monday, February 25, 2008 7:48:17 PM Imar Spaanjaars said:
Hi bharathi,

Did you make any modifications to the code? It should work out of the box.

The error is a very generic one; there could literally be hundreds or thousands of reasons for that error. Maybe you're better off posting this on a forum like p2p.wrox.com and supply a more detailed problem description and the offending part of the code.

Cheers,

Imar
On Monday, March 10, 2008 8:31:21 AM isuru said:
just used the code, works fine. very compatible with vs2005 and sql2005. nice one, thanx :)
On Monday, April 14, 2008 10:20:05 AM jack said:
Hi.

This is a good article to start with.

but i dont know how to achieve these snenarios?

may be you can help me out of this problem.

i want to add this funtion in my userregistration.aspx page.

<snip>Long explanation cut by Imar</snip>

i hope your getting my point.

thanks.

jack.
On Monday, April 14, 2008 11:21:40 AM Imar Spaanjaars said:
Hi Jack,

Yes, I got your point. However, it seems you're missing too much ASP.NET foundation to get started, which makes it difficult for me to explain what to do over a single post.

May I recommend you check out my latest book Beginning ASP.NET 3.5?

You can find more info about it here: http://imar.spaanjaars.com/AboutMyBooks.aspx?aboutitem=beginningaspnet35

Cheers,

Imar
On Tuesday, May 27, 2008 8:22:48 PM tries said:
Great article!  Will it work for Office 2007 files?  For instance, the ContentType for a word doc is application/vnd.openxmlformats-officedocument.word and not the typical application/msword.

Thanks,
tries
On Friday, May 30, 2008 5:34:40 PM Imar Spaanjaars said:
Hi tries,

Yes I think it would work, provided you change the code to include the new content type.

But why don't you try it and let me know? ;-)

Cheers,

Imar
On Tuesday, June 03, 2008 12:03:16 AM scott said:
HI,

I have implemented a file upload page and a file download page in my site. This is storing PDF, ZIP, DOC and XLS files to my SQL DB in binary format. I need to find a way to delete them from my DB. Using a standard SQL Delete query does not work. This is because the files are not physical files but stored in binary format in the DB itself. Can you tell me the correct procedure for Deleting these type of uploaded files from the DB.


Thanks.
On Tuesday, June 03, 2008 5:35:52 AM Imar Spaanjaars said:
Hi scott,

A standard DELETE query should work fine. It deletes the entire record and its associated file / attachments:

DELETE FROM Files WHERE Id = 123

Should do the trick.

Cheers,

Imar
On Saturday, June 14, 2008 7:41:01 AM Anto said:
hi
I would like to view the image with all other details from the DB
But the image occupying the whole page
Can i bind the image with an image control?

could u explain...?

On Saturday, June 14, 2008 9:20:53 AM sachin zade said:
I like this artical.
sir i have prob with bytes data,


acutully i have save mp3 file into database in byte format
now i want to store this file to folder how can i store this bytes to folder help me

thanks in advance
On Sunday, June 15, 2008 5:04:03 PM Imar Spaanjaars said:
Hi sachin and Anto,

I have no idea what you are asking. Can you try a support forum like http://p2p.wrox.com?

Cheers,

Imar
On Thursday, August 07, 2008 3:53:00 PM Joey said:
Is there anyway that i could resize the image or reduce on upload to the SQL server to conserve space on the server? This would help me out alot!
On Monday, August 11, 2008 7:37:38 PM Joey said:
Bitmap b = (Bitmap)Bitmap.FromStream(new MemoryStream(ByteArray));
Bitmap output = new Bitmap(b, new Size((b.Width / 2), (b.Height / 2)));
//Resize Image
System.IO.MemoryStream stream = new System.IO.MemoryStream();
output.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
          
stream.Position = 0;
byte[] data = new byte[stream.Length];
stream.Read(data, 0, (int)stream.Length);
On Tuesday, August 26, 2008 5:49:41 PM Omair said:
Hi Imar,

I'm wandered to your website after having been stuck in a problem. I've managed to setup my application so that when a user uploads a local file, its stored in a folder on our server. However, I also want it to be stored in a table in our DB. But I have no idea how to do that. Even after reading, I'm sort of confused. Im a new developer so my knowledge is also very limited, I'm sort of learning.

What do you think I should do?

Thanks,
Omar
On Tuesday, August 26, 2008 9:03:15 PM Imar Spaanjaars said:
Hi Omair,

This whole article *is* about storing files in a database, so it's difficult for me to suggest something to do if this article doesn't help you. You're not really explaining what you're having difficulties with and I can't really believe that after reading this article you really "have no idea how to do it".

Maybe you should get a good introduction book into programming like Beginning C# or my own "Beginning ASP.NET 3.5"?

Imar
On Wednesday, August 27, 2008 12:31:12 PM Atul Awasthi said:
hi omar,
i just want to know that if we have to upload audio, video, document, graphics and animation by same browser in sql server 05 then what type of data type should we take?
On Wednesday, August 27, 2008 4:17:20 PM Imar Spaanjaars said:
Hi Atul,

Omar? Who is Omar? My name is Imar.

Anyway, did you really read this article before you posted this comment? Try again, and focus on the section titled "Storing the Files". It's all in there.

Cheers,

Imar
On Saturday, August 30, 2008 10:29:10 AM azhari said:
Dear,
I enabled database for datastoretype. and when i uploaded one file to database, the code uploaded the file two times. is there any comment?
thank you for ur great help.
On Sunday, August 31, 2008 9:22:54 PM Imar Spaanjaars said:
Hi azhari,

Difficult to tell without seeing code. Can you post this on a forum like http://p2p.wrox.com?

Cheers,

Imar
On Monday, September 15, 2008 5:50:37 AM Bogdan said:
Hello.

I would like to add some new columns to the table such that the user that posted a picture to can modify the rows that picture. I am a beginner so i need some help.

Best wishes,
Bogdan
On Monday, September 15, 2008 6:31:29 AM Imar Spaanjaars said:
Hi Bogdan,

Adding fields shouldn't be too hard, I think. You can create a copy of the ContentType column for example at all places (class, database table, stored procedure and so on) and then fill it with the data the user entered.

If that doesn't help, may I suggest you get a good beginner's book like Beginning ASP.NET 3.5?

Cheers,

Imar
On Monday, September 15, 2008 6:45:17 AM Bogdan said:
Hello Imar,

Look what i have done and why i have some problems. My first idea was to add some more columns to the file table in the code you posted. I thought then that i can let the user to edit a line in the table after uploading an image because in those columns i need a kind of description of the picture beacuse I want to make a fishing site.
I used a sqldatasource not an objectdatasource instead.

After compiling i got the following error : Date type is not supported by your sql version.


If you don`t mind could you tell me what files do i also have to modify excepting the table ?

Thank you for your response.
On Monday, September 15, 2008 6:57:22 AM Bogdan said:
I may send you the code to see my error it is very strange for me this error
On Monday, September 15, 2008 7:01:07 AM Imar Spaanjaars said:
Hi Bogdan,

Is that the exact error message, spelling and all? I doubt that's the case as Google returns exactly 0 hits for:

"Date type is not supported by your sql version"

May I suggest you post this on a forum like http://p2p.wrox.com?

Much easier to post code there, and others will be able to help out as well.

Cheers,

Imar
On Monday, September 15, 2008 7:12:18 AM Bogdan said:
The version of SQL Server in use does not support datatype 'date'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: The version of SQL Server in use does not support datatype 'date'.

Source Error:



I have a thought that the following lines are the problems: (i wrote HERE where i guess is the problem)

            [asp:Parameter Name="original_ContentType" Type="String" /]
    HERE-->    this line is the problem  [asp:ParameterDbType="Date"Name="original_DateCreated" /]
On Monday, September 15, 2008 7:16:07 AM Imar Spaanjaars said:
Hi Bogdan,

What part of "May I suggest you post this on a forum" did you not understand?

Anyway, sounds like the code is targeting SQL 2008. Try this instead:

Type="DateTime"

Hope this helps,

Imar
On Monday, September 15, 2008 7:22:15 AM Bogdan said:
I admire your amability omar.
It doesn`t help.

All the best,
Bogdan
On Monday, September 15, 2008 7:25:08 AM Imar Spaanjaars said:
Hi Bogdan,

omar? Who's omar? My name is Imar....

Imar
On Monday, September 15, 2008 12:00:08 PM azhari said:
Hi Imar,
I solved the problem.
thank u very much.
On Monday, September 15, 2008 2:11:23 PM Imar Spaanjaars said:
Hi azhari,

That's great. Would you mind telling us *how* you solved the problem?

Cheers,

Imar
On Monday, September 15, 2008 5:18:34 PM Imar Spaanjaars said:
Hi Bogdan,

Have you posted this on a forum so I can take a look?

Cheers,

Imar
On Wednesday, September 17, 2008 2:23:10 PM azhari said:
Hi Imar,
I found that i used OnClick property in the button tag, at the same time i handled Click event in code behind of the button.
thanks
On Thursday, September 18, 2008 6:30:45 AM Bogdan said:
Hy Imar,

I posted here http://forums.aspfree.com/net-development-11/error-to-my-web-application-244417.html

Best wishes
On Thursday, September 18, 2008 7:32:18 AM Imar Spaanjaars said:
Hi Bogdan,

So it was Type="DateTime" as I suggested this problem after all, right?

Imar
On Thursday, September 18, 2008 7:39:57 AM Bogdan said:
Yes and no.. Because after modifying it appeared another error so I didnt work at all to my site from then because I didnt find any solution.

Bogdan
On Thursday, September 18, 2008 7:53:06 AM Imar Spaanjaars said:
But does my code download work?

Imar
On Thursday, September 18, 2008 8:32:57 AM Bogdan said:
Yes, until the step you want to update something in the table
On Thursday, September 18, 2008 8:37:23 AM Imar Spaanjaars said:
Are you saying it doesn't work when you download the source code and try to run it? That is, doesn't the code work when you run it without any modifications?

Imar
On Thursday, September 18, 2008 10:00:26 AM Bogdan said:
It works fine after download. The problem is when you add an edit option to a gridview and try to update a field.

Bogdan
On Saturday, September 20, 2008 2:36:14 PM Imar Spaanjaars said:
Hi Bogdan,

My original code doesn't support updating, so the problem has to be with some code you added yourself. Without seeing that code it's pretty difficult to say what the problem is. Have you tried Googling for the error message to see what it means? If you understand that, it's easier to diagnose your code and see what might be causing the problem.

Anyway, try posting this, with code, on http://p2p.wrox.com and I'll take a look.

Cheers,

Imar
On Sunday, September 21, 2008 6:54:33 AM Bogdan said:
Hello,

Can you tell me how to modify to support updating ?
On Sunday, September 21, 2008 8:20:13 AM Imar Spaanjaars said:
Hi Bogdan,

That's quite a broad topic and since I don't know what you already know and don't know, it's pretty difficult to do over a comment post as this one.
So, as I suggested earlier: can you post this on http://p2p.wrox.com? On a forum, it's much easier to post code, explain your problem, provide error messages and get help from a broader group of helpful people.

Cheers,

Imar
On Wednesday, September 24, 2008 10:55:21 PM waseem said:
i try  that coad but it didn,t work on my side it give me error that is

"An error has occurred while establishing a connection to the server"

please help me out why that occur so here on my side

thanks regard
On Thursday, September 25, 2008 9:37:47 PM Imar Spaanjaars said:
Hi waseem,

Sounds like you don't have a SQL Server instance called .\SqlExpress installed.

Download and install SQL Server Express or update the connection string to match your version of SQL Server

Cheers,

Imar
On Wednesday, December 17, 2008 4:43:55 PM David said:
Hi

Found this very useful. I downloaded your sourcecode for c#, and when I commented out the database settings in the web.config file the uploaded files still get saved to the database.

What am I doing wrong lol

David
On Wednesday, December 17, 2008 6:04:21 PM Imar Spaanjaars said:
Hi David,

Difficult to say from here..... The code depends on the connection string in web.config, so it looks like you commented out the wrong setting....

Imar
On Monday, December 22, 2008 6:20:49 PM Imran said:
hi imar...I'm a beginner in asp  now I'm working with asp file upload and save this file to SQL Server database . But the files can be uploaded to 4 mb and "Server Application Unavailable Error" is shown, but i 've to upload big size files . what would I do. I've tried Server.ScriptTimeout = LargeNumber* ....it doesn't work.

*LargeNumber = ?

I think u may give a solution.

**another problem...  there is no tool for messagebox textfield in my visual studio...what can i do to make messagebox
On Monday, December 22, 2008 7:47:00 PM Imar Spaanjaars said:
Hi Imran,

Search these comments for maxRequestLength to fix the size problem.

With regards to the toolbox, try resetting the Toolbox or your VS settings. Can't help much more than that; I try to answer questions related to my articles, but I don't provide support for VS and this site is also not a technical forum.... ;-)

Cheers,

Imar
On Tuesday, December 30, 2008 4:05:28 AM Mrs. CB Spira said:
Mr. Spaanjaars,
A bit of an intro:
I'm designing a web site for a web programming class I'm taking (using your Beginning ASP.NET 3.5 as the textbook - it's been wonderful!)

A DB was a requirement for the project, and in my design document I indicated that there would be a repository of lectures that the user would be able to listen to. Given that this is only a class assignment I sought out a free .asp host that provided db support. I finally found one - but there's a restriction on uploading media files (wav, mp3) - and a huge penalty if they realize that the file name was tampered with. I do not want to lose points due to not implementing the design that I created so here's my question:

Would storing the media files within the database effectively circumvent the host's restrictions? There is nothing nefarious or illegal about the files - I just need them to be audio or video media that my professor can see on a live and functional site.

Many thanks,
Mrs. CB Spira
On Tuesday, December 30, 2008 8:54:29 AM Imar Spaanjaars said:
Hi Mrs. CB Spira,

To be honest? I have no idea as I didn't make up the rules.... ;-) I think you're much better off asking your host.

Whether you store files on disk or in a database, you still need to upload the files. So, if they are tracking uploaded files, you're probably breaking their rules. But only your host can tell for sure....

Cheers,

Imar
On Tuesday, December 30, 2008 3:49:11 PM Mrs. CB Spira said:
Thank you so much for your prompt reply :-)

Your answer makes sense - but since it's a "free" account there doesn't seem to be too much support (or leeway) for asking such questions... Oh well, I'll have to take it up with my professor after all..

Thanks for your time...
Mrs. CB Spira
On Tuesday, December 30, 2008 5:10:15 PM Imar Spaanjaars said:
Hi Mrs. CB Spira,

You're welcome....

Good luck finding the answer, and Happy New Year!

Imar
On Thursday, January 08, 2009 2:52:02 AM swapnil said:
hi.........

thanks for the post........

i got what i am searching from many days....

thanx again....
On Saturday, January 10, 2009 9:25:19 AM swapnil said:
hey the post is greatest one thanx.......!!!!!!1

bt i have 1 problem that how to run that project in visual studio because the .prj file is not present inside the project folder........

plz reply soon........
On Saturday, January 10, 2009 9:30:43 AM Imar Spaanjaars said:
Hi swapnil,

It's not a Web Application Project with a *proj file; it's a Web Site Project. Simply choose File | Open Web Site in Visual Studio.

Cheers,

Imar
On Tuesday, January 13, 2009 12:10:14 AM swapnil said:
hi Imar

i have tried the application it's great post...thnx

bt i have come across one problem that my files doesn't get uploaded into a d/b when i click on "Add new file"

so plz reply.....

thnx in advance....

On Tuesday, January 13, 2009 6:46:39 AM Imar Spaanjaars said:
Hi swapnil,

But does it get uploaded to disk? You need to configure the application properly in web config. Also, make sure the account used by the web server (most likely: you or the Network Service account when using IIS) has permissions to write in the App_Data folder.

Cheers,

Imar
On Wednesday, January 14, 2009 4:28:12 AM swapnil said:
hi Imar

i m using that application on my pc using visual studio 2005

i had created the file named abc.txt which i have browsed through the quickdocid and clicked on upload file but the list remains as it is.........


it doesn't upload my file.....

plz help me........

how to upload file from my pc?????

thanx in advance....
On Wednesday, January 14, 2009 6:22:57 AM Shraddha said:
Nice Article I got to say. As such I like your book instant results also. I'm developing a job portal and I want the users to upload resumes along with other fields and allow him/her to modify his resume next time he visits the site. So how can I coordinate this fileupload facility along with other form elements..this is my major concern. I also want to allow them to modify their resumes online. i.e..when they click they are able to open it online as a document. Can you help me Imar Spanjaars as I'm new to asp.net 2.0
thanks and regards
shraddha
On Wednesday, January 14, 2009 7:19:41 AM Imar Spaanjaars said:
Hi swapnil,

If you download, unzip and run the application, it should work out of the box, provided that the App_Data folder is writable.

I don't understand what you mean with "browsed through the quickdocid".

If you keep having troubles, can you post this on a forum like http://p2p.wrox.com and provide more information about your setup, actual code and so on?

Cheers,

Imar
On Wednesday, January 14, 2009 7:22:49 AM Imar Spaanjaars said:
Hi Shraddha,

First of all, my name is Imar Spaanjaars, not Imar Spanjaars.

Secondly, I am not sure what you'e asking, or why you're asking it. Isn't this all in this article? That is uploading files, showing them on the site and so on?

If you're really new to ASP.NET, may I suggest you get a book like Beginning ASP.NET 3.5  using C# and VB.NET (no point in getting a 2.0 book anymore). That way, you'll better understand the basics, and my Instant Results book and this article.

Cheers,

Imar
On Wednesday, January 14, 2009 7:47:19 AM Shraddha said:
Hi,
Sorry for the wrong spelling and thanks for your reply. I have one issue which is troubling me that I want the users to update the resume without giving them an option to download as well as saving it back again..to the directory as well as database whereas in your application I'm unable to do that. Any changes made are not saved. Since I have already designed the class files and fileupload option also............ I want that upon revisit the end user is able to modify it and I need to incorporate all these in my existing class files. I need an expert's guide like you.
thanks and regards
shraddha
On Wednesday, January 14, 2009 8:22:32 PM Imar Spaanjaars said:
Hi there,

Well, I am not going to write the code for you. This article should give you pretty much everything you need to build what your requirements dictate with regards to uploading and saving files. If you need more help with stuff like user management, securit, business logic on how to "find" a specific user's documents and so on, check out the books I suggested earlier.....

I write articles, but I am not your on-line free consultant. Sorry.....

Cheers,

Imar
On Thursday, January 15, 2009 12:18:00 AM swapnil said:
hi Imar,

i just wnt to ask u that does this application from my self pc when i m running that application in visual studio?

because when i want to upload the file i have already created on my pc then it's not get uploaded in the database and also it doesn't show the name of it on the home page of the application.......


please help me....

thanx in advance.....!!!!!!
On Thursday, January 15, 2009 7:15:57 AM Shraddha said:
Hi Imar,
I totally agree with ur point and even if u don't reply me I'll thankfull to you for the wonderful article. Actually my concern is how to get back the uploaded file with its original name and format. If you can tell me how can I achieve that I'll be greatful to you.
Thanks
shraddha
On Thursday, January 15, 2009 7:16:16 AM Imar Spaanjaars said:
Hi swapnil,

while (true)
{
  RepeatSameQuestion();
  GiveSameAnswer();
}

We're in a loop. Yes, it works out of the box. Yes, there's nothing else you need to do other than:

1. Unzip
2. Choose File | Open Web Site in VWD 2008
3. Make sure App_Data is writable
4. Hit F5

And yes, I cannot really say anyting useful based on the messages you're posting. All you say is" it doesn't work". That's pretty difficult to analyze and fix don't you think?

So please, for the last time before I start deleting your posts:

1. Go to p2p.wrox.com
2. Start a new thread and post full details on your setup, installation, the way you open the files, browse to the site and so on. Give details on your OS, the file structure, the version of Visual Studio, the way you open the file in the browser, the way you browse to the file to upload and so on and so forth. Without this information, nobody can help you.

Cheers,

Imar
On Thursday, January 15, 2009 7:19:27 AM Imar Spaanjaars said:
Hi Shraddha,

It depends. You can't, really, other than letting the user choose one of the files that were uploaded earlier. There's no way to connect a file uploaded by the browser to one in the database, other than by its name which might not be unique enough.

Imart
On Monday, January 19, 2009 11:48:04 AM Soufiane Abdellaoui said:
Hi Imar,
I am using a List from System.Collections.Generic library to store a collection of MyFile.  Then I bind the List to the BindingSource, which is connected to the GridView.  

I need to sort & filter my list based on user input.  I tried setting the BindingSource.Filter property and it had absolutely no effect.    Based on what I’ve found on the Internet, it seems like the collection object has to implement IBindingListView interface in order to provide filtering capabilities.  And of course the List from System.Collections.Generic doesn’t.   Is this correct?  Is there an easy way of doing this?  Is the filtering supported by DataReader?  
On Monday, January 19, 2009 12:32:59 PM Imar Spaanjaars said:
Hi Soufiane,

AFAIK, the BindingSource only makes sense in connected architectures, like WinForms.

However, it's pretty easy to accept user input and forward that to a stored procedure that filters the data at the database level.

Cheers,

Imar
On Monday, January 19, 2009 2:43:01 PM Soufiane Abdellaoui said:
Hi Imar,

Thanks for your quick reply.
I use exactly the same as in your article, and I want to sorting an filter the GridView with two  DropDownList .

Please help me!

PS: I work in my thesis and it is very important
On Monday, January 19, 2009 2:47:08 PM Imar Spaanjaars said:
Hi Soufiane,

Sorting and filtering is dealt with in part 4 of this article series: http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=476.

You can wait for it to appear on-line (couple of days), or buy the entire article series now:
http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=482

Cheers,

Imar
On Monday, January 19, 2009 4:06:17 PM Shraddha said:
Hi Imar,
I have a problem when I tried to execute your FileShare application(Instant Results). I tried with your your provided username and password....in the book but I get error.."Index was out of bounds Array". Can you please tell where am I wrong.?.bcoz recently my IIS created problems so I had to uninstall and re-install it again..and I guess it might be the cause of the error. Bcoz after that I had to run aspnet_regiis -i at the command prompt to regain localhost permissions etc..
thanks
shraddha
On Monday, January 19, 2009 4:12:26 PM Imar Spaanjaars said:
Hi Shraddha,

I didn't write that chapter, so I don't know what's going wrong. Did you check the errata? http://www.wrox.com/WileyCDA/WroxTitle/ASP-NET-2-0-Instant-Results.productCd-0471749516,descCd-ERRATA.html

There's a similar error for a different chapter (the first entry). Maybe that's the same issue?

If not, can you please post this in the book's own forum on p2p.wrox.com?

Cheers,

Imar
On Wednesday, April 29, 2009 10:12:15 AM karuna said:
how can i store a file in databse (ms access) from winforms
On Wednesday, April 29, 2009 7:05:34 PM Imar Spaanjaars said:
Hi karuna,

I don't have any ready made code for that, but search Google for "store file access .NET" and you'll find lots of useful artciles.

Cheers,

Imar
On Saturday, May 30, 2009 4:09:58 PM rajab said:
hi.

in App_Code\AppConfiguration.vb

Return DirectCast([Enum].Parse(GetType(DataStoreType), ConfigurationManager.AppSettings.[Get]("DataStoreType"), True), DataStoreType)

. @this point i got an error:

ArgumentNullException

Value cannot be null. Parameter name: value

with best regards
On Saturday, May 30, 2009 4:19:59 PM Imar Spaanjaars said:
Hi rajab,

Maybe you don't have that value in your web.config? Otherwise, you'll need to do some debugging to see where it breaks as I can't tell from this code.

Cheers,

Imar
On Sunday, May 31, 2009 8:46:52 AM rajab said:
there are differencies with vb code and c#code in webconfig @appsetting section. i solved my problem . thanks a lot
On Sunday, May 31, 2009 9:11:36 AM Imar Spaanjaars said:
Hi rajab,

I am not sure what you mean. The C# and VB.NET web.config files are identical, except that they each default to another store type (e.g. FileSystem versus Database). Can you elobarate on what the problem was? Or was it in your own implementation and not in my code?

Imar
On Thursday, June 11, 2009 11:32:03 AM azhari said:
how to upload only text or documnet files?
On Thursday, June 11, 2009 6:04:25 PM Imar Spaanjaars said:
Hi azhari,

You can use a Regular Expression to validate the file's extension right before you call SaveAs and reject the file when it has an extension you don't want to allow.

Cheers,

Imar
On Tuesday, June 16, 2009 10:18:39 PM Jennifer said:
First of all, this code is fantastic!! Thank you so much for taking the time to post this.

I'd like to have the gridview display only the files that correspond with the record that I'm viewing.  I've changed the code to save a corresponding recordid in the db when uploading the files but I'm unsure of how to set a parameter inside of the fileinfo ... GetList

I've added the three lines of code that add sql parameters but I'm unsure of how to set the value.  

I tried setting "Select Parameters" in the ObjectDataSource but I get an error saying "odsFiles could not find a non-generic method 'GetList' that has parameters: @RequestID"

So I'm not declaring the parameters properly I would assume.

Any help?

Thanks in advance.
On Thursday, June 18, 2009 4:14:10 PM Jennifer said:
Nevermind, figured it out. (If anyone else is wondering, add a parameter under SelectParameters and the name doesn't include the '@' symbol.)

Thanks again for this great how to.
On Tuesday, June 23, 2009 5:34:48 PM Jennifer said:
Hello again,

I've used your code to upload files to my database and then display certain files based on an id that I've implemented.  Now I would like to be able to take those files and send them as attachments in an e-mail.

I'm thinking of using a for/next statement that loops through the rows in the gridview and adds an attachment for each row.  However, I'm unsure of how to do this.

Any ideas?  (Also, I'm using vb.net, but if C# is easier for you I'm good with that as well.)

Thanks in advance.
On Wednesday, June 24, 2009 5:42:45 AM Imar Spaanjaars said:
Hi Jennifer,

Take a look here:

http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=412

It shows you how to directly add Stream instances to the Attachments collection of an e-mail message.

Cheers,

Imar
On Wednesday, June 24, 2009 1:48:52 PM Jennifer said:
Hello Imar,

Thanks for your response, I'm actually not getting the stream from the file upload control.  Basically I have a summary page of information that was submitted by the user.  A manager can go in and select to e-mail this page to another person.  

So I need to figure out a way to get the fileID, go to the database, grab the file data, and attach that to the e-mail.

I have a for statement that looks like this:
  For i = 0 To Me.gvFiles.Rows.Count - 1
            Dim filename As String = gvFiles.Rows(i).Cells(3).ToString
            Dim fileid As Byte() = StringToByteArray(gvFiles.Rows(i).Cells(0).ToString)
            Dim id = New Guid(fileid)
            Dim myFile As File = File.GetItem(id)
            Dim InputStream = myFile.FileData
            msg.Attachments.Add(New Attachment(InputStream.ToString, filename))
        Next

   Public Shared Function StringToByteArray(ByVal input As String) As Byte()
        Return Encoding.Unicode.GetBytes(String.Empty + input)
    End Function

I get an error with this code that says: "Byte array from GUID must be exactly 16 bytes long."  

I don't think I can get information from the gridview, instead I think I need to use the classes that you have created, I'm just unsure of how to do this.

Thanks in advance for any help.
On Wednesday, June 24, 2009 5:48:35 PM Imar Spaanjaars said:
Hi Jennifer,

Correct, you probably don't want to get it from the GridView. Why not use the method that gets the data from the database and feeds it to the GridView in the first place?

And why is the FileId a Byte()? It's simply a Guid so this *might work:

Dim fileid As Guid = New Guid(gvFiles.Rows(i).Cells(0).ToString())

In this case, a new Guid is constructed from a string representation.

But, like I said earlier, using GetList would be a lot simpleter as you get direct access to the File instances and their Ids.

Hope this helps,

Imar
On Saturday, June 27, 2009 7:24:12 AM ram said:
how to save and get the image to asp.net 2.0 with sql server2005 at code behind vb
On Saturday, June 27, 2009 9:32:09 AM Imar Spaanjaars said:
Hi ram,

Heuh? Not sure what you're asking. Aren't all the concepts you need explained in this aticle?

Imar
On Tuesday, June 30, 2009 4:33:23 PM Jennifer said:
Hello again Imar,

I'm still working on e-mailing attachments after they're saved to the file system and this is what I have so far:

        Dim myList As List(Of FileInfo) = Nothing
        myList = FileInfo.GetList(intRequestID)
        For i = 0 To myList.Count - 1
            Dim filename As String = myList.Item(i).OriginalName
            Dim fileid = myList.Item(i).Id
            Dim myFile As File = File.GetItem(fileid)
            Dim InputStream As Stream = ??????
            msg.Attachments.Add(New Attachment(InputStream, filename))
        Next

I'm not sure how to get the InputStream of a stored file.  I originally thought that if I duplicate how you did it in the file class while saving it might work (Dim InputStream as Stream = New MemoryStream(myfile.fileData))  but I get an error saying the buffer size cannot be null.

Any ideas?

Also, right now I'm working on localhost, will users still be able to save files to the file system when this is released?

Thanks again in advance,
Jennifer
On Tuesday, June 30, 2009 4:42:41 PM Imar Spaanjaars said:
Hi Jennifer,

If they are stored on disk, why don't you add them using file based syntax? E.g.:

msg.Attachments.Add(new Attachment("C:\Somefile.gif"))

You can get the physical file name of the File instance by calling something like:

Server.MapPath(myList.Item(i).FileUrl)

And yes, this should work on a production server as well, provided you have sufficient permissions to read and write files.

Cheers,

Imar
On Tuesday, June 30, 2009 5:22:08 PM Jennifer said:
Imar,

You are brilliant. Ha, I can't believe I forgot the easy way of attaching files with a simple fileurl.  

Thank you again,
Jennifer
On Tuesday, June 30, 2009 6:29:09 PM Imar Spaanjaars said:
Hi Jennifer,

You're welcome. You would only use the Stream if you were retrieving files from the database.

Cheers,

Imar
On Wednesday, July 08, 2009 10:32:40 PM Jennifer said:
Hello again Imar,

Turns out, I need to use a database to store my files.  Do you have any idea as to what the code looks like when getting the Stream from the fileData in the database?

Thanks in advance.
On Thursday, July 09, 2009 9:06:17 PM Imar Spaanjaars said:
Hi Jennifer,

Take a look at the section that describes how the files can be saved to disk as well based on the fileData.

Cheers,

Imar
On Sunday, September 20, 2009 12:53:42 PM Madhu said:
Hi Mr. Imar,

Thanks for your link. Its really rocks. And I just wondered why my jpg formats which is uploaded are not possible to view. But its able to download only. How can I make those jpg formats also possible to view?

Sorry to trouble you again
On Sunday, September 20, 2009 1:00:16 PM Imar Spaanjaars said:
Hi Madhu,

Same answer as in my private e-mail message to you: I don't know what you're talking about. That hasn't suddenly changed.....

Imar
On Sunday, September 20, 2009 1:23:06 PM Madhu said:
Hi Mr. Imar,

Sorry again. Its my mistakes. I am uploads the files from the VWD. And checking through whether can view or not. From there itself not possible to view. And I closed the VWD and open the app. Its possible to view and download.

Once again thanks for your patience
On Monday, September 21, 2009 10:21:25 PM Rodney Santiago said:
Hi,

I accidentally unsubscribed to this Doc. How do get back on the mailing list?

Thanks,
rodchar
On Tuesday, September 22, 2009 6:01:54 AM Imar Spaanjaars said:
Hi Rodney,

If you checked "Notify me of replies" when posting this message, you're subscribed again now. There's no way to manually subscribe to an article without posting a comment first.

Cheers,

Imar
On Tuesday, November 24, 2009 9:13:34 AM Asad said:
Hi,
    It's a wonderful job u have done. Its helped so much

Thank u so much
On Wednesday, December 16, 2009 4:05:16 PM julio65 said:
hi, i would like someone to help step by step  on how to store and retrieve files from the database using a gridview to download them but without using Classes and stored procedures but only using query statements
On Thursday, December 17, 2009 10:20:43 PM Imar Spaanjaars said:
Hi julio65,

The code should contain enough information to figure this out. Just take the code from the stored procedures and rewrite it as in-line SQL.

Not sure I understand why you wouldn't want to use classes though.

Cheers,

Imar
On Sunday, December 27, 2009 4:14:11 PM julioass said:
hi experts iwould like you to help me on how to retrieve Doc files from sql database using sql statement  onto  gridview and aswellas downloading via a link from the gridview.
thax
On Sunday, December 27, 2009 4:18:21 PM Imar Spaanjaars said:
Hi julioass,

Heuh? Isn't that exactly what this article is about?

Cheers,

Imar
On Friday, January 08, 2010 12:29:02 PM fred smith said:
How can i add a text box to the page that someone can type there name into and save the text box info in the data base files. ID of txt box is txtName and the Name added to table files is Name. So now when you upload the file the persons name is also in the data base Please help with thank you
On Saturday, January 09, 2010 10:04:52 AM Imar Spaanjaars said:
Hi fred,

You can modify this code to make that work. Just take a copy of an existing column (such as the fileUrl) and add it where necessary (in the database, the sprocs, the class and so on).

Cheers,

Imar
On Saturday, January 09, 2010 9:42:55 PM fred smith said:
thank you for anwering back OK i think I understand, you stated:  You can modify this code to make that work. Just take a copy of an existing column (such as the fileUrl) and add it where necessary (in the database, the sprocs, the class and so on).

Is there any way you could give me a small example please?
(asp:TextBox ID="txtName" runat="server"(/asp:TextBox)
in database add to srocFileInsertsingletem: @name, then  there are the classes: File.cs (private string Name;) When where?, FileInfo.cs (private string Name;) When where?, AppConfiguration.cs (does not seem it need it) ??, saving the txtname to the database please help need please??



On Sunday, January 10, 2010 10:08:21 AM Imar Spaanjaars said:
Hi fred,

Take a look at the code and follow the originalName property. Everywhere that is used, create a copy for your property (e.g. in the classes, constructor, stored procedure, ASPX pages and so on).

Then you get it from the text box like this:

string userName = txtUserName.Text;

and pass it to the constructor:

File myFile = new File(contentType, originalName, fileData, userName);

From there, you can treat it like any other property of the File class.

Hope this helps,

Imar
On Monday, January 11, 2010 12:35:18 AM fred smith said:
thank you the string userName = txtUserName.Text; added to the uploadfile.cs was missing it is working. I am learning Form you thank you it is fun......

Could you tell me please with a small exsample how to add it to the view grid in the Default.aspx file to view info please.

I went to the fileinfo and added but maybe i am missing something. I also add the UserName to the SpocselectList. What do I need or missed to view the new add info in the File data base called UserName???


On Monday, January 11, 2010 12:03:47 PM fred smith said:
How About a Delete button on the grid?? does it have to be done in a class or can you just call it from the grid view.

Could you please give a line or two SAMPLE of the code please?? so i can try it??
On Thursday, January 14, 2010 1:50:45 AM fred smith said:
Response.WriteFile(Path.Combine(AppConfiguration.UploadsFolder, myFile.FileUrl));

get error

  // Get the name without folder information from the uploaded file.
Line 35:             string originalName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Line 36:
Line 37:             // Get the name without folder information from the uploaded file.

Compiler Error Message: CS0103: The name 'Path' does not exist in the current context

Puting the file to a master page I get an error. How do I link this file and the download file to work in with a master page please????

Below at the (path) cant find the path it this point???

Response.WriteFile(Path.Combine(AppConfiguration.UploadsFolder, myFile.FileUrl));
On Thursday, January 14, 2010 8:32:41 AM Imar Spaanjaars said:
Hi fred,

You need to add a using statement for the System.IO namespace.

With regards to your other questions, check out http://www.asp.net/learn/ or get yourself a copy of my book Beginning ASP.NET 3.5 in C# and VB.

Cheers,

Imar
On Thursday, January 14, 2010 9:33:05 AM fred smith said:
I have worked out the other questions, and yes i will buy your book were do i get it??

Can you please give me an exsample of using statement for the System.IO namespace?????

Where do I add it Please to work so it will function with a master page (using System.IO;) and getting the path to find itself (Response.WriteFile (Path.Combine AppConfiguration.UploadsFolder, myFile.FileUrl));

Please give a little sample to direct me ??????
On Thursday, January 14, 2010 9:41:47 AM Imar Spaanjaars said:
Hi fred.

Just add:

using System.IO;

in the code file that is trying to use the Path class.

With regards to the book, check out Amazon:

http://www.amazon.com/Beginning-ASP-NET-3-5-C-VB/dp/047018759X

Cheers,

Imar
On Tuesday, March 16, 2010 10:13:47 AM priya said:
ya, its working . very nice . thanks a lot
On Tuesday, March 30, 2010 3:06:39 PM kalpana said:
Thank you very much sir
On Wednesday, March 31, 2010 4:14:27 PM Joshua said:
Imar,

Thanks for the article.  When I try to save a Office 2007 file (word or excel) the web app saves it fine.  When I try to download or view the file it is corrupt and I cannot open it.

Any ideas?
On Monday, June 28, 2010 5:14:15 PM Daniel Gomez said:
Guys, Congratulations on this Program, but i have a little issue when trying to list all the uploaded files;
In fact when i uploaded a file it's shows perfectly BUT when the file is deleted from the source, it keeps showing it such as it will still there.
any Suggestion or what do i have to do to avoid that
Thanks in advance and PLEASE HELP!!!! ;)
On Monday, June 28, 2010 5:38:17 PM Daniel Gomez said:
help me with the Q above
On Monday, June 28, 2010 5:52:59 PM Imar Spaanjaars said:
Hi Daniel,

Don't push me with "help me" follow up posts; if and when I have the time, I reply. Otherwise, you just have to wait.

Anyway, sounds llike a caching issue to me. Does the item go away when you do a hard refresh in the browser?

Imar
On Tuesday, August 10, 2010 7:20:29 PM Imar Spaanjaars said:
For anyone following the posts on this article by e-mail: I just posted a newer version of the File application using a Provider Model. You find the article here: http://imar.spaanjaars.com/414/storing-uploaded-files-in-a-database-or-in-the-file-system-with-aspnet-20

Cheers,

Imar
On Tuesday, August 31, 2010 10:34:25 PM Michael said:
Hello Imar;
Great work that you are doing thanks for giving so much of your time to help us all learn.
Another user posted this same issue (On Wednesday, March 31, 2010 4:14:27 PM Joshua said:
Imar,
Thanks for the article.  When I try to save a Office 2007 file (word or excel) the web app saves it fine.  When I try to download or view the file it is corrupt and I cannot open it.
Any ideas?
)
I have read all comments and did not find a reply to this question.

The Microsoft Office Word message is:
The Office Open XML file (filename) cannot be opened because there are problems with the contents.

It then gives the options of  "OK" or "Details>>>"

Taking the Details option shows
"The file is corrupt and cannot be opened"

Taking the "OK" option
"Word found unreadanle content in (filename). Do you want to recover the contents of this Document? "Yes" or "No". "
Yes will open the file...

I have searched the net for answers and cannot find one. Is this an issue with Office 2007?
On Wednesday, September 01, 2010 6:22:08 AM Imar Spaanjaars said:
Hi Michael,

Don't know why that would happen. I just tested it on my machine and it seems to work fine.

When exactly does this happen? When you store files on disk or in the database? In the former case, are the files on disk still OK? E.g. is it an upload or a download issue? And are you using the C# or the VB version?

Imar
On Monday, October 04, 2010 6:03:45 PM Arthur said:
Hi, I'm not a programmer and I have a question: how to modify your code to retrieve the table parameters such as GridView1 or Label1.
Regards, Arthur
On Monday, October 04, 2010 8:48:36 PM Imar Spaanjaars said:
Hi Arthur,

I don't understand your question.

Cheers,

Imar
On Tuesday, October 05, 2010 9:27:02 AM Arthur said:
I want the table Files add 2 columns.
For example: column "Who" will retrieve data from Label1, column "NewId" will retrieve data from GridView1.
On Tuesday, October 05, 2010 9:37:47 AM Imar Spaanjaars said:
Hi Arthur,

This still doesn't make any sense to me. Try posting your question on a forum such as this one: http://p2p.wrox.com/index.php?referrerid=385 and be sure to provide a lot more detail.

Cheers,

Imar
On Tuesday, October 05, 2010 12:46:37 PM Arthur said:
I'm sorry you do not understand.
I want to link a table Files from another table.
On Tuesday, October 05, 2010 12:49:15 PM Imar Spaanjaars said:
Yes, don't we all.

Please follow my advice; I can't help you here as you can't seem to express what it is that you want.

Imar
On Wednesday, October 06, 2010 5:16:06 AM Arthur said:
Ok. I'll try to explain.
I want the table to have information about the logged on user. The code that I added is not valid: the table appended is NULL. My code:
Dim Label1 As New Label
myCommand.Parameters.AddWithValue("@who", Label1.Text.ToString)
On Wednesday, October 06, 2010 6:33:20 AM Imar Spaanjaars said:
Hi Arthur,

What part of "Try posting your question on a forum ... and be sure to provide a lot more detail" did you not understand and made you decide to continue the discusion here instead?

Even after a number of requests, you're not making much sense and certainly are not providing a lot more detail. Please take this discussion elsewhere. I'll delete future posts from you on the same topic.

Cheers,

Imar
On Wednesday, October 06, 2010 6:41:05 AM Arthur said:
Does this mean that you can not or do not want to help me? Or maybe it's not your code and can not modify it?
On Wednesday, October 06, 2010 6:44:03 AM Imar Spaanjaars said:
Hi Arthur,

I can and want to help you, but apparently you don't want to be helped because you don't listen to my advice. And I cannot help if you if I don't understand what it is what you want. is that so hard to understand?

>> Or maybe it's not your code and can not modify it?
What's that supposed to suggest? That this content isn't mine or genuine?

Imar
On Monday, October 18, 2010 6:01:58 AM ariel said:
I just wanna ask.....I just download the source code,,i did not found the database in the file...but it is working...where is the database located?
On Monday, October 18, 2010 7:04:11 AM Imar Spaanjaars said:
Hi ariel,

Pure magic..... Or it could be the database file in the standard ASP.NET App_Data folder..... ;-)

Imar
On Wednesday, October 20, 2010 1:29:15 AM ariel said:
Hi,,,,thanks for the answer,,,I wanna ask again,,,where did the file located after adding new file?.....im just curious where it is saved?...and also can we delete the file?
On Wednesday, October 20, 2010 7:04:14 AM Imar Spaanjaars said:
Hi ariel,

Why don't you just read the article and the comments (search for delete). The answers are all in there....

Imar
On Tuesday, November 23, 2010 3:28:21 PM Chester said:
Am building an application for an Estate agency and am finding it very hard to upload a picture straight to the database using visual basic application 2005

Your quick responds will be highly appreciated

Chester
On Tuesday, November 23, 2010 4:57:38 PM Imar Spaanjaars said:
Hi Chester,

The only quick response on a question like this is "and the problem is what exactly"?

Try posting this on a forum such as this one: http://p2p.wrox.com/index.php?referrerid=385. If you do, be sure to provide a lot more detail about your current code and the problems you run into.

Did you notice this article comes with the full source code in VB?

Imar
On Wednesday, November 24, 2010 2:56:12 PM Manu said:
Hi, my question is:
How can I display a database stored image (image type) in a asp:image control?

I have seen that the below functions are used in a new page to view the image, but I want to upload it and view it in the same page in an asp:image control.

Response.AppendHeader
Response.ContentType
Response.OutputStream.Write
On Wednesday, November 24, 2010 3:19:27 PM Imar Spaanjaars said:
Hi Manu,

You can't. An image control renders HTML and needs a src attribute that in turn points to an image, or a dynamic handler or page. E.g.:

<img src="SomeHandler.ashx?Id=123" />

You could directly embed an image using DATA URIs but I wouldn't do that because of browser support and cachability: http://www.websiteoptimization.com/speed/tweak/inline-images/

Cheers,

Imar
On Wednesday, November 24, 2010 3:48:58 PM Manu said:
Ok well, forgetting about viewing the image in the same page;

The only way to view an image in an asp:image control is by opening a new page? And in the new page, how do I convert the file stream(the binary data of the image) to an URL, so the asp:image control can display the image ?
On Wednesday, November 24, 2010 4:04:25 PM Imar Spaanjaars said:
>> The only way to view an image in an asp:image control is by opening a new page?

Technically: no, as you could embed the image as explained in the article I linked to.

Practically: yes. You need a separate resource (such as a handler or a page) that is used as the ImageUrl for the control. You assign the URL as per my previous example (although that uses an img tag, the idea is the same) and stream the image as I've explained in this article in the part about viewing files.

Cheers,

Imar
On Wednesday, November 24, 2010 6:25:02 PM Manu said:
Hi again, im trying to use a handler for what i want but i cannot use query string or use session varibles.

How can i access the ID of the image from the handler?
On Wednesday, November 24, 2010 7:02:31 PM Manu said:
Never mind, i got what i wanted. Thanks a lot!!

I cannot make a Request("ID") from the handler, instead i had to make context.Request.QueryString("ID") to retrieve the query string from the handler.
On Tuesday, December 28, 2010 1:33:24 PM Daniel Brewerton said:
Is there a way to use an existing 2005/2008 SQL Server instead of the included SQL file?
On Tuesday, December 28, 2010 3:55:30 PM Imar Spaanjaars said:
Hi Daniel,

You certainly can. Just create the necessary objects in your database (a table and three stored procedures) and point the connection string in web.config to your database.

To make the first part a little easier, I created a script for you that you can run against your database. You find the script here:

http://imar.spaanjaars.com/Downloads/Articles/WorkingWithFiles/WorkingWithFilesSqlScripts.zip

Cheers,

Imar
On Tuesday, December 28, 2010 4:00:24 PM Daniel Brewerton said:
That is what I figured but I saw an object in the db explorer and wasn't sure if it was required. Awesome and many thanks! I had one thought, maybe you could expand on this to permit for multiple file uploads?
On Tuesday, December 28, 2010 4:06:56 PM Imar Spaanjaars said:
Hi Daniel,

Dealing with multiple files is really simple; just loop over Request.Files and execute most of the code in btnUpload_Click. Each item in the loop is an HttpPostedFile which is also what's used in FileUpload1.PostedFile.

Hope this helps,

Imar
On Friday, January 07, 2011 7:20:52 PM Rodger said:
Hey Imar,

Thanks for a great article and I appreciate your patience in dealing with all the responses.

I have a question with an error once opening an MS word file that was stored using vb into SQL File stream. All is done via the correct standards, but something is not quite as it should be.

The issues is:
When you retrieve a file from the database, copy it to disk and open it a message in Word appears saying that "The file xyz.docx cannot be opened because there are probelms with the contents." The details say that "The file is corrupt and cannot be opened."
But the file was just added from this computer.

I know that this is not the scope of the article, but i have been looking for an answer to this for the past 2 months and have not found anything. Your article came up in the most recent search so I thought that there may be something here.

The Question:
Do you know of anyway that word headers are messed with when a file is uploaded to a SQL database? or can you point me in the direction of where to look.

Many Thanks,
Rodger
On Friday, January 07, 2011 9:55:47 PM Imar Spaanjaars said:
Hi Rodger,

Hard to tell without seeing your code.

I would look into the way the file is saved and retrieved, and compare them using some diff program and see if that sheds some light.

Sorry, can't help much here.

Cheers,

Imar
On Friday, January 07, 2011 10:04:59 PM Rodger said:
Thanks, will compare code in detail.

One blog changed

byte[] writeBuffer = templateMemoryStream.GetBuffer();
to:
byte[] writeBuffer = templateMemoryStream.ToArray();

for it to work, but that was c# so maybe it is something similar and small. Will keep looking.

Thanks for considering
On Thursday, January 13, 2011 12:48:17 PM Daniel Brewerton said:
What I'd like to know is how to modify the code to use a querystring value. I'm providing the querystring by this method:

http://localhost/myform/form.aspx?Request_ID=1

I have added this request_id field to the database tables but how do I get the method to accept this value?
On Thursday, January 13, 2011 2:08:32 PM Imar Spaanjaars said:
Hi Daniel,

Not exactly sure what you're asking. The code already uses a Query String parameter to retrieve the selected file. Are you talkiing about changing the type of the parameter from a Guid to an int? If so, that requires some changes in GetItem and the stored procedure that it calls.

Cheers,

Imar
On Thursday, January 13, 2011 2:12:16 PM Daniel Brewerton said:
Not changing that one but adding another one. I have added an extra field into that table which is my Request_ID.
On Thursday, January 13, 2011 2:14:55 PM Imar Spaanjaars said:
Hi Daniel,

In that case, you can create a copy of GetItem (an overload) and have it accept an integer. Then you need to copy the code that it calls to support the integer as well.

Cheers,

Imar
On Tuesday, January 18, 2011 7:51:25 PM Daniel Brewerton said:
Ok, I have tried what you suggested but now I'm getting an error:
ObjectDataSource 'odsFiles' could not find a non-generic Method 'GetList' that has parameters: ReqFormId.

Code modified:
Added Phone_ReqFormId as int to match db

Added this parameter to stored proc

Changed GetItem to include Query String variable.
On Wednesday, January 19, 2011 7:42:53 AM Imar Spaanjaars said:
Hi Daniel,

Looks like you modified too much. You shouldn't have touched GetList, only GetFile, the method that gets a single item from the database. GetList should be able to continue as before; all it does is get a list of FileInfo instances.

But why not simply replace the Guid id with an integer? That would have been a lot simpler....

Cheers,

Imar
On Wednesday, January 19, 2011 10:56:04 AM Daniel Brewerton said:
One of the things I love most about VS is the ability to go back. Reverted my changes and will try again.
On Wednesday, January 19, 2011 11:03:44 AM Daniel Brewerton said:
I've been looking not only at my own modified code but also the original. I can't find the GetFile method. Can you show me where this code is? Thanks :)
On Wednesday, January 19, 2011 11:05:09 AM Imar Spaanjaars said:
Sorry, I meant GetItem, as suggested in my earlier comments.

Imar
On Wednesday, January 19, 2011 11:12:33 AM Daniel Brewerton said:
Ok, now the biggest question I have in this case is if I have multiple files with the same request ID, will modifying the code have the desired effect? The RequestID field applies to multiple database items so naturally I'm curious.
On Wednesday, January 19, 2011 11:52:37 AM Imar Spaanjaars said:
Hi Daniel,

Depending on how you implement things, the answer is probably: No. Since I don't know what RequestID is used for, I can't recommend much. If you want to be able to retrieve multiple files based on the same RequestID, you need to modify GetList instead. Each individual file can then be retrieved by its Id (the Guid, as it currently is).

If this doesn't help, please post this on a forum such as this one: http://p2p.wrox.com/index.php?referrerid=385 and be sure to provide more detail and code if applicable.

Cheers,

Imar
On Wednesday, January 19, 2011 12:06:45 PM Daniel Brewerton said:
Ok, I will give that a go. Thank you. :)
On Wednesday, January 19, 2011 6:22:32 PM Daniel Brewerton said:
Ok, I posted to the wrox forums. I'm really stumped and frustrated.

[http://p2p.wrox.com/c-2008-aka-c-3-0/82292-trying-work-imars-file-manager.html]
On Wednesday, January 19, 2011 6:30:44 PM Angela said:
This has saved me some major time! Thank you so much.

I do have a problem though...and this has been mentioned already, but I didn't see an answer and I was just wondering if anyone ever figured it out.

When I click the View link to view a .docx document, I receive the following error:

The XML page cannot be displayed
Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.


--------------------------------------------------------------------------------

An invalid character was found in text content. Error processing resource 'http://testgalaxy/WorkingWithFilesVB/ViewFile.as...
On Wednesday, January 19, 2011 7:01:48 PM Imar Spaanjaars said:
Hi Angela,

Does your Word document work fine when you download it normally? If so, you could force a download of the document, rather than a "view in browser".

Cheers,

Imar
On Wednesday, January 19, 2011 8:42:41 PM Angela said:
That seems to work fine. I will try it that way.
On Thursday, March 17, 2011 8:13:16 AM Daniel Brewerton said:
Just a quick question, is there some way this could have an anti-leech script attached to the links being generated? Any suggestions of a free anti-leech asp.net code that would do the job?
On Thursday, March 17, 2011 8:15:37 AM Imar Spaanjaars said:
Hi Daniel,

Don't know of any ready-made solutions (although I am sure they exist). In the past I wrote my own checking the HTTP Referer, but that's not fool-proof.

Cheers,

Imar
On Monday, April 25, 2011 2:09:23 AM mahendra said:
how i create delete method in asp.net using your project logic
On Monday, April 25, 2011 2:57:16 AM Imar Spaanjaars said:
Hi mahendra,

Read the comments on this article to get some ideas. Additionally check out the follow-up article I wrote, linked at the top of the article.

Cheers,

Imar
On Monday, April 25, 2011 10:14:51 AM Rodger Beadle said:
Hi Imar,

I found the solution on opening word files that i had been struggling with (per above). When opening files using Bytes and the byte length, bt sure to use the length - 1...

Thanks,
Rodger

Dim fs As New FileStream(FileName, FileMode.CreateNew, FileAccess.Write)
            fs.Write(byData, 0, byData.Length - 1)
            fs.Close()
On Tuesday, April 26, 2011 9:05:19 AM Meera said:
Dear Imar,

The code works perfectly when incorporated into my application, but the only problem is that when a 'text' file is viewed, it appends the 'View Source' (HTML code) of the ASPX web page itself.  
Any ideas as to why.

Appreciate any help.

-MD
On Tuesday, April 26, 2011 9:26:01 AM Imar Spaanjaars said:
Hi Meera,

That's really strange. Can you post the relevant bits of your code on a forum such as http://p2p.wrox.com so I can take a look?

Cheers,

Imar
On Monday, July 11, 2011 2:00:40 AM mani said:

Im using asp.net and vb.net

please find solution to my question.

outside the grid we have a button called Attach, when we click
the button the files should browse and then selected file should be display in gridview.

Thanks in advance
On Monday, July 11, 2011 1:33:10 PM Imar Spaanjaars said:
Hi mani

Euhm, hello? Did you read the artice? Isn't this *exactly* what the article is about?

Imar
On Wednesday, September 21, 2011 3:51:16 AM Shaheen Ur Rehman said:
hi,
anyone can tell me i m developing a simple page contain name, phonenumber, email and image so one exception came.any one can help me?
this is my code
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;

public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context)
    {

        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings
                               ["uploadimage"].ConnectionString;
        SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select Name,PhoneNumber,Email,Image from saveimage" +
                  " where ID =@ID";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;

SqlParameter ImageID = new SqlParameter
                    ("@ID", System.Data.SqlDbType.Int);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.ContentType = dReader["Name"].ToString();
context.Response.ContentType = dReader["PhoneNumber"].ToString();
context.Response.ContentType = dReader["Email"].ToString();
context.Response.BinaryWrite((byte[])dReader["Image"]);
dReader.Close();
con.Close();
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}
exception is givenbelow
The parameterized query '(@ID int)Select Name,PhoneNumber,Email,Image from saveimage wher' expects the parameter '@ID', which was not supplied.
On Wednesday, September 21, 2011 4:25:11 AM Imar Spaanjaars said:
Hi there,

Two things you can try:

1. Make sure that context.Request.QueryString["ID"] contains a valid value

2. Try adding the Parameter without the @ symbol.

If this doesn't help, I don't know what's going on.

Cheers,

Imar
On Wednesday, September 21, 2011 4:35:32 AM Daniel Brewerton said:
Friend, you may want to look at this link. To use a querystring as a parameter, you have to delcare it correctly or code behind won't find it.

if (Request.QueryString["id"] != null)

objCommand.Parameters.Add(new SqlParameter("@id", Request.QueryString["id"]));
else

objCommand.Parameters.Add(new SqlParameter("@id", DBNull.Value

http://forums.asp.net/t/1339866.aspx/1?Problem+with+SqlParameter+and+Request+QueryString
On Wednesday, September 21, 2011 4:38:25 AM Imar Spaanjaars said:
Hi Daniel,

This is a Handler, so you won't be able to access Request like that. Instead, you need context.Request as the OP is already using. In addition, I would abort the entire transaction when there's no ID rather than passing DBNull.Value.

Cheers,

Imar
On Thursday, October 27, 2011 2:24:47 PM alakya said:
Very good article. It saves lot of time gives many ideas for implementation.
Instead of creating constructors in "File" vb file.  can we use  all the public properties and calling stored procedures in database layer.
On Wednesday, November 02, 2011 11:50:20 AM Bryan said:
Intresting Article.if it has to be added to a aplication which is using sql 2000.
What can be used for varbinary(max) for FileData?
On Wednesday, November 02, 2011 4:11:05 PM Imar Spaanjaars said:
Hi Bryan,

Check out the section under the heading "Storing the Files".

Cheers,

Imar
On Thursday, November 10, 2011 4:12:16 AM vaibhav said:
can u tell me how i can display this uploaded file with in all browsers
On Thursday, November 10, 2011 4:18:01 AM Imar Spaanjaars said:
Isn't that exactly what this article is about?

Imar
On Wednesday, November 16, 2011 9:52:54 AM Jim claws said:
Great knowledge. Your books are awesome. Thanks for your time to share. In sql Database all the upload loaded  files are stored in binary format or consuming bytes?
On Wednesday, November 16, 2011 12:42:55 PM Imar Spaanjaars said:
Hi Jim,

>> the upload loaded  files are stored in binary format or consuming bytes?

Both....

Imar
On Friday, November 25, 2011 9:51:48 AM kumaramc@hotmail.com said:
GOOD ARTICLE
On Tuesday, November 29, 2011 3:49:53 PM Nelson said:
Hi

I'm trying to implement it in a way that:  when they browse and click upload file, it should not save to the  database. It should save to database when they click  other save button  on the page.

I tried to implement it in this way but the file properties always return null reference exception. I'm unable to retrieve the parameters in "Save button click function" from File Class properties. I'm looking to save all  other data in the page and file upload in single button click 'save'.  Could you please advise me
On Tuesday, November 29, 2011 4:37:56 PM Imar Spaanjaars said:
Hi there,

In that case you need to store the file on disk temporarily, as it's only uploaded the first time, not after a postback.

Cheers,

Imar
On Monday, December 05, 2011 8:10:34 PM Jim said:
Hi Imar,

Jim Again
Can please give me a hint  to store the file on disk temporarily unitil save button click. Thank you.

On Monday, December 05, 2011 8:49:18 PM Imar Spaanjaars said:
Hi Jim,

Just make up a random file name (using Guid.NewGuid() for example), store the file on disk using SaveAs, and remember the file location. Then on post back, do whatever you need to do with the stored file.

For more ideas, look into the documentation of the FileUpload class and the System.IO namespace.

Cheers,

Imar
On Thursday, January 05, 2012 2:48:21 PM Barry said:
Hi Imar,

Great sample application you have created, I am wondering through.

Do you have a bare bones VB version which only caters for filesystem up/downloads?

Im trying to strip this out but finding it to be less easy than first thought.

Thanks.
On Tuesday, January 24, 2012 6:56:27 AM Kalyan said:
Hi ,
In my application am using c#.net with out using database. this am doing for intranet ,my query is:
I have created a folder called " backup " in app_data ..in my application,in that folder am uploading files using file-upload..according to the needs..now i want to display those files in data grid with link button or only link button..if i click that link button the file should save in my file system like save as...what are the files in backup folder should be displayed as links...step by step..
any one please help me in this...
Thanks
Kalyan
On Tuesday, January 24, 2012 7:05:56 AM Imar Spaanjaars said:
Hi there,

Files stored in App_Data are *not* directly accessible to the browser. This is by design. Either save them somewhere else, or stream them as I do with the ones from the database.

>>click that link button the file should save in my file system like save as

If by this you mean save without user intervention: forget it. That would be a major security issue.

>> what are the files in backup folder should be displayed as links...step by step..

Sorry, it doesn't work this way. I am not a on-demand coder.... ;-)
But you'll find anything you need to accomplish your tasks (except for saving the file without user intervention) in this article.

Cheers,

Imar

On Tuesday, January 24, 2012 7:46:20 AM kalyan said:
Hi Imar,
Thanks for ur valuable time ..
this is not that much security website...
just for example..in app_data i have backup folder...in that folder i have 3 files for example...call as a.txt,b.txt.c.txt...these files should display in my page ...the file is not necessary to open ...i just want to show all files  in page. if i click any file it should be saved in file system...

for uploading i used this code

protected void Btnoffline_Click(object sender, EventArgs e)
    {
        if (Flpload.PostedFile.FileName == "")
        {
            lblstatus.Text = "No file specified.";
        }
        else
        {
            try
            {
                string serverFileName = Path.GetFileName(Flpload.PostedFile.FileName);

                Flpload.PostedFile.SaveAs(MapPath("~/App_Data/backup/") + serverFileName);
                lblstatus.Text = "File " + serverFileName;
                lblstatus.Text += " backup  file uploaded successfully.";
            }
            catch (Exception err)
            {
                lblstatus.Text = err.Message;
            }

        }
    }

now here upload of backup file is over ...so this process will continue daily...now next issue is that to see those uploaded files some where in any control or page...and if click those files it should save some where..
thanks
kalyan



On Friday, January 27, 2012 1:46:53 PM Imar Spaanjaars said:
Hi there,

I don't think you understood my previous reply. Files stored in App_Data *cannot* be accessed by the browser directly. Instead, you'll need to create a page that contains code that reads these files and then streams them back to the browser, similar to what I am doing with the files in the database. Look at methods in the File class to see how to do this.

Also, you can't save files automatically; once you download a file you'll get a Save As dialog that lets you choose a location.

>> this is not that much security website...

It's not about the site, but about the browser. Imagin I could save files on your disk without your approval....

Cheers,

Imar
On Tuesday, February 28, 2012 7:51:15 AM satish said:
thanks i need to this code for file upload in asp.net websiter
again thanks
On Wednesday, May 30, 2012 7:23:57 PM manzur said:
sir i want to upload and play the videos in asp.net c# pages which should be load from the database. plz help me it very urgent....
On Wednesday, May 30, 2012 7:30:29 PM Imar Spaanjaars said:
Hi manzur,

If it's so urgent, why don't you read this article and try out the code? Everything you need to build this is described in this article in full detail.

Cheers,

Imar
On Wednesday, July 18, 2012 4:48:27 PM Dwight said:
Hi Imaar,

I am looking for a way to upload multiple files in one go.

For example, I want to be able to open the File Dialog and then using "Ctrl", select multiple files.

I would also like to preselect only certain file extensions.

I am working with Visual Studio 2005 and .NET 2.0

Do know how to do this?

Thank you.
On Wednesday, July 18, 2012 7:02:03 PM Imar Spaanjaars said:
Hi Dwight,

Take a look here: http://imar.spaanjaars.com/567/uploading-multiple-files-at-once-using-aspnet-45

This does require HTML 5 though, (and .NET 4.5 if you want to use server controls).

Alternatively, there are upload controls that use Flash or other client technologies to make this possible.

Cheers,

Imar
On Tuesday, November 06, 2012 1:44:36 AM Joan said:
Hi! Your article's great! Have learned a lot from it. But I have a question.. If for example I have saved two files that are the same, I only want to display the file with the recent date, and therefore hide the other file.. How to do that? "MAX(FileDate) AS Expr1" is not working.. Thank you.
On Tuesday, November 06, 2012 11:30:34 AM Imar Spaanjaars said:
Hi Joan,

Givem a table with three columns: Id, FileName and FileDate, the following query would give you the most recent version of each file name:

SELECT        Id, FileName, FileDate
FROM            Files AS f
WHERE        (FileDate =
                             (SELECT        MAX(FileDate) AS Expr1
                               FROM            Files AS f2
                               WHERE        (FileName = f.FileName)))

If that doesn't work for you, Google for "sql find latest record" and you'll find lots of useful suggestions.

Cheers,

Imar
On Wednesday, November 07, 2012 12:33:08 AM Joan said:
Hi imar.. Thanks for the reply.. My columns are ID, Name and Type only.. I dont have column for the Date.. If I have two same files, I only want to fetch the file with the latest ID, because ofcourse it is the latest version of that file.. Need help :(((

Thank you!
On Thursday, November 08, 2012 1:18:15 AM Joan said:
Hi imar! I got already the answer. No need to reply! It is: SELECT MAX(DocID) AS DocID, DocName, Type FROM SaveDoc GROUP BY DocName, Type ORDER BY DocID DESC

By the way, thank you for your post! :)
On Thursday, November 08, 2012 8:16:36 AM Imar Spaanjaars said:
Hi Joan,

Good to hear you found a solution.

Cheers,

Imar
On Monday, March 10, 2014 9:20:27 PM Josh said:
Hi,

Is it possible to link your Files DB to another table? I am trying to use your File manager with another table to view the uploaded file for each record.

Thanks
On Monday, March 10, 2014 9:27:33 PM Imar Spaanjaars said:
Hi Josh,

What you mean "with another table"? You can simply configure the database in the config file, and update the sprocs to match your table.

Or are you looking for a code free solution to that? If so, that's not supported. You'll at least need to update the stored procedures.

Cheers,

Imar
On Monday, March 17, 2014 12:04:08 PM manikandan said:
hi!
how to send resume connect access database using in asp.net
On Monday, March 17, 2014 3:39:18 PM Imar Spaanjaars said:
Hi manikandan,

I have no idea what you're asking. Can you elaborate?

Imar
On Wednesday, April 09, 2014 2:08:37 PM valkrs said:
Hi Imar! Your article is great! Have learned a lot from it. But I have a question:

I'm a student and I've read your book Beginning ASP.NET 4.5 : in C# and VB and now I'm trying to create a project "e-Library".

Based on your book, I'm using two tables you created: Instead Genre table I'm using Book and the Review table stays as it is.

Everything works fine and each review has a Title as a book title and inside a review I'm showing book description, pages, author, format, publisher..etc,.

Now, I'm trying to use this article you wrote and give each review a PDF file where a user can download it.

First, I'm saving all uploaded files on the management section. Now I just need a 'Download' button on the client side.

To make it simple can I download directly from the Uploads folder using placeholders where the placeholder is replaced with the name of the book?...just to give you an idea.

Then, do I need to include the Files table to the Entity Framework Data Model?

The problem is that this Files table is a separate table and your book uses SqlDataSources and LINQ to Entities to access data in the database.

I know it's hard to answer this question but can you give me an idea on how can I integrate this on my project.
On Friday, April 11, 2014 3:03:52 PM Imar Spaanjaars said:
Hi valkrs,

You may want to take another look at the Photo Albums section in my book as it shows how to store files on disk, save a link to them in the database, and the provide the ability for users to view / download them from the Uploads folder (GigPics in the book).

Does that help? If not, can you clarify your question? I am currently not sure what you're trying to achieve, or what the exact question is.

Cheers,

Imar
On Saturday, April 12, 2014 8:25:06 PM valkrs said:
Thanks for reply Imar!

Yes, that's exactly what I'm looking for. I started a new thread at Wrox Forum.

I'm sure you will help me there, as you do always.

Best regards.

Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.

For more information about the Talk Back feature, check out this news item.