C# Getting Files from the Client
Use the File Field HTML control to upload files from the client to the server. The File Field HTML control is actually a Text Field
HTML control and a Submit Button HTML control bound together. Clicking the Browse button runs a built-in script that displays
the Windows Choose File dialog box on the client's computer.
To receive the selected client file on the server, follow these steps
1. Draw a File Field HTML control on a Web form.
2. Right-click the control, and select Run As Server Control from the shortcut menu
3. Right-click the Web form, and select View HTML Source. Visual Studio displays the HTML code for the Web form
4. Add an "enctype" attribute to the <form> tag in the Web form's HTML. The "enctype" attribute sets the MIME type
of the form, and uploading a file requires both a MIME type of "multipart/for-data" and a form method of "post", as
shown here: v---------this section--------------------v
<form action="webform1.aspx" method="post" enctype="multipart/form-data" runat="server" ID="Form1">
5. Right-click the Web form, and select View Design from the shortcut menu. Visual Studio displays the Web Forms Designer.
6. Add a Button control and a "Click" event procedure to the Web form to get and save the selected file. For example, the
following procedure saves the file to the server:
NOTE: Make sure you create the folder you are saving to on your server, or you will get an error
private void butUpload_Click(object sender, System.EventArgs e)
{
string strFilename;
try
{
// Get the file name.
strFilename = filUpload.PostedFile.FileName;
// Exit if no file name was entered
if (strFilename == "") return;
// if file is zero length, it is empty or doesn't exist
if (filUpload.PostedFile.ContentLength == 0)
{
lblMsg.Text = "File was not found on client or file contains no data.";
return;
}
// Get the base name for the file (exclude path)
strFilename = System.IO.Path.GetFileName(strFilename);
// Save uploaded file to server
filUpload.PostedFile.SaveAs(Request.MapPath("./uploadedfiles") + "\\" + strFilename);
// Add file to list of server files.
lstServerFiles.Items.Add(strFilename);
// Select an item in the list
lstServerFiles.SelectedIndex = 0;
}
catch (System.UnauthorizedAccessException ex)
{
lblMsg.Text = "You must set the permissions on the server to allow the ASPNET user to write to the destination folder.";
}
catch (Exception ex)
{
lblMsg.Text = "An unexpected error occurred: " + ex.Message;
}
finally{}
}