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

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 1/11/2007 2: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 1/11/2007 2: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 1/13/2007 2: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 1/13/2007 7: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 1/14/2007 9: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 1/14/2007 10: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 1/17/2007 11: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 1/19/2007 6:40:33 AM okboy said:
THANK YOU VERY MUCH..
I need this feature for my application....

On Monday 1/22/2007 7: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 1/22/2007 8: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 2/1/2007 4:02:26 PM Greg Fibiger said:
Thanks Imar for the information under appsettings

On Sunday 2/4/2007 4: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 2/4/2007 2: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 2/4/2007 3: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 2/4/2007 6: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 2/4/2007 11: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 2/5/2007 6: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 2/5/2007 7: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 2/5/2007 3: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 2/5/2007 7: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 2/5/2007 9: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 2/7/2007 6: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 2/7/2007 7: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 2/8/2007 10: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 2/9/2007 6: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 2/9/2007 6: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 2/12/2007 8: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 2/13/2007 1: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 2/13/2007 8: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 2/14/2007 4: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 2/16/2007 2: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 2/16/2007 10: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 2/22/2007 3: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 2/26/2007 5: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 2/26/2007 7: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 2/26/2007 8: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 2/26/2007 9: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 2/28/2007 10: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 2/28/2007 10: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 3/3/2007 1: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 3/3/2007 11: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 3/6/2007 7: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 3/6/2007 10: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 3/12/2007 5:35:11 AM briiin said:
Hi, Imar, Brilliant. Thanks alot.

On Thursday 3/15/2007 2: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 3/15/2007 2: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 3/15/2007 4: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 3/15/2007 4: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 3/29/2007 8:04:05 PM David Country said:
U da man,

Holla at ur boyee

On Tuesday 5/8/2007 6: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 5/8/2007 6: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 5/8/2007 11: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 5/8/2007 11: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 Thursday 5/10/2007 12:35:59 AM 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 Friday 5/11/2007 12:18:34 AM Imar Spaanjaars said:
Hi there,

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

Imar

On Saturday 5/12/2007 1:53:36 PM 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 5/14/2007 12:40:06 PM 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 5/14/2007 12:52:03 PM 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 5/14/2007 3: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 5/14/2007 10: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 5/16/2007 6: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 5/16/2007 8: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 5/19/2007 6: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 5/19/2007 9: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 5/20/2007 7: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 5/20/2007 9:49:51 PM Imar Spaanjaars said:
Hi Azhari,

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

Imar

On Monday 5/21/2007 9: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 5/21/2007 9: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 5/30/2007 1:24:37 PM 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 5/30/2007 1:37:54 PM 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 5/30/2007 4: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 5/30/2007 4:32:42 PM Imar Spaanjaars said:
Hi azhari,

How is this related to this article?

Imar

On Wednesday 5/30/2007 4: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 5/30/2007 4: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 5/30/2007 6: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 5/31/2007 4: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 6/3/2007 4: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 6/3/2007 10: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 6/3/2007 10: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 6/10/2007 11: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 6/11/2007 7: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 6/11/2007 11:31:33 AM Maryam said:
Thanks Imar,
It was greate help from you.
Sincerely,
Maryam

On Friday 6/15/2007 3: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 6/15/2007 3: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 6/15/2007 7: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 6/21/2007 11:26:54 AM kapil sharma said:
thanks yarr that is great detail fo uploading files.

On Thursday 7/5/2007 1:47:56 PM 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 7/5/2007 4: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 7/5/2007 4: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 7/5/2007 4: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 7/5/2007 4: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 7/25/2007 8:15:17 AM srinath reddy.M said:
it's too000000 good

On Wednesday 8/1/2007 5: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 8/1/2007 11: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 9/7/2007 1:13:41 PM 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 9/7/2007 2: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 9/7/2007 2: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 9/10/2007 10: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 9/10/2007 10: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 9/10/2007 11: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 9/10/2007 11: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 Tuesday 9/11/2007 12:17:22 AM 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 Tuesday 9/11/2007 12:23:14 AM 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 9/14/2007 11: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 9/14/2007 11:57:51 AM Imar Spaanjaars said:
Hi vipn,

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

Imar

On Monday 9/24/2007 7: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 9/24/2007 8: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 10/2/2007 1:16:31 PM 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 10/2/2007 1:22:01 PM 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 10/14/2007 8: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 10/15/2007 7: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 10/25/2007 11: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 10/25/2007 11: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 Friday 10/26/2007 12:23:12 AM 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 Friday 10/26/2007 12:33:51 AM 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 11/13/2007 5: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 11/13/2007 9: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 1/16/2008 1: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 2/25/2008 12:53:59 PM 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 2/25/2008 8: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 3/10/2008 9:31:21 AM isuru said:
just used the code, works fine. very compatible with vs2005 and sql2005. nice one, thanx :)

On Monday 4/14/2008 12:20:05 PM 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 4/14/2008 1:21:40 PM 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 5/27/2008 10: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 5/30/2008 7: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 6/3/2008 2: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 6/3/2008 7: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 6/14/2008 9: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 6/14/2008 11: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 6/15/2008 7: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 8/7/2008 5: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 8/11/2008 9: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 8/26/2008 7: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 8/26/2008 11: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 8/27/2008 2: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 8/27/2008 6: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 8/30/2008 12:29:10 PM 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 8/31/2008 11: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 9/15/2008 7: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 9/15/2008 8: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 9/15/2008 8: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 9/15/2008 8: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 9/15/2008 9: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 9/15/2008 9: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 9/15/2008 9: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 9/15/2008 9:22:15 AM Bogdan said:
I admire your amability omar.
It doesn`t help.

All the best,
Bogdan

On Monday 9/15/2008 9:25:08 AM Imar Spaanjaars said:
Hi Bogdan,

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

Imar

On Monday 9/15/2008 2:00:08 PM azhari said:
Hi Imar,
I solved the problem.
thank u very much.

On Monday 9/15/2008 4: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 9/15/2008 7: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 9/17/2008 4: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 9/18/2008 8: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 9/18/2008 9:32:18 AM Imar Spaanjaars said:
Hi Bogdan,

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

Imar

On Thursday 9/18/2008 9: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 9/18/2008 9:53:06 AM Imar Spaanjaars said:
But does my code download work?

Imar

On Thursday 9/18/2008 10:32:57 AM Bogdan said:
Yes, until the step you want to update something in the table

On Thursday 9/18/2008 10: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 9/18/2008 12:00:26 PM 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 9/20/2008 4: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 9/21/2008 8:54:33 AM Bogdan said:
Hello,

Can you tell me how to modify to support updating ?

On Sunday 9/21/2008 10: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 Thursday 9/25/2008 12:55:21 AM 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 9/25/2008 11: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 12/17/2008 5: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 12/17/2008 7: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 12/22/2008 7: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 12/22/2008 8: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 12/30/2008 5: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 12/30/2008 9: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 12/30/2008 4: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 12/30/2008 6: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 1/8/2009 3:52:02 AM swapnil said:
hi.........

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

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

thanx again....

On Saturday 1/10/2009 10: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 1/10/2009 10: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 1/13/2009 1: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 1/13/2009 7: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 1/14/2009 5: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 1/14/2009 7: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 1/14/2009 8: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 1/14/2009 8: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 1/14/2009 8: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 1/14/2009 9: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 1/15/2009 1: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 1/15/2009 8: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 1/15/2009 8: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 1/15/2009 8: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 1/19/2009 12:48:04 PM 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 1/19/2009 1: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 1/19/2009 3: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 1/19/2009 3: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 1/19/2009 5: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 1/19/2009 5: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 4/29/2009 12:12:15 PM karuna said:
how can i store a file in databse (ms access) from winforms

On Wednesday 4/29/2009 9: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 5/30/2009 6: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 5/30/2009 6: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 5/31/2009 10: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 5/31/2009 11: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 6/11/2009 1:32:03 PM azhari said:
how to upload only text or documnet files?

On Thursday 6/11/2009 8: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 Wednesday 6/17/2009 12:18:39 AM 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 6/18/2009 6: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 6/23/2009 7: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 6/24/2009 7: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 6/24/2009 3: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 6/24/2009 7: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 6/27/2009 9: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 6/27/2009 11: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 6/30/2009 6: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 6/30/2009 6: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 6/30/2009 7: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 6/30/2009 8: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 Thursday 7/9/2009 12:32:40 AM 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 7/9/2009 11: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 9/20/2009 2: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 9/20/2009 3: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 9/20/2009 3: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 Tuesday 9/22/2009 12:21:25 AM Rodney Santiago said:
Hi,

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

Thanks,
rodchar

On Tuesday 9/22/2009 8: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 11/24/2009 10:13:34 AM Asad said:
Hi,
    It's a wonderful job u have done. Its helped so much

Thank u so much

On Wednesday 12/16/2009 5: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 12/17/2009 11: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 12/27/2009 5: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 12/27/2009 5:18:21 PM Imar Spaanjaars said:
Hi julioass,

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

Cheers,

Imar

On Friday 1/8/2010 1: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 1/9/2010 11: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 1/9/2010 10: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 1/10/2010 11: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 1/11/2010 1: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 1/11/2010 1: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 1/14/2010 2: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 1/14/2010 9: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 1/14/2010 10: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 1/14/2010 10: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

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 CAPTCHA image now. This means that if you want to leave a comment, you'll need to type in the text you see on the image. If you can't see the text clearly, click the New Image button to get an image with a new text. For more details, see this news item.

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


Captcha Image - Please type the text from the image in the text box
Can't see the text on the image? Click the New Image button to display a new image with different text.