Protected void cmdUpload_Click (object sender, EventArgs e)
{
// Check if a file was submitted.
If (Uploader. PostedFile. ContentLength! = 0)
{
Try
{
If (Uploader. PostedFile. ContentLength> 1048576)
{
// Limit the file size here
// File Upload is limited to 4 MB
// If the value is larger, use the maxRequestLength attribute set in
LblStatus. Text = "Too large. This file is not allowed ";
}
Else
{
// Upload to the Upload path
String destDir = Server. MapPath ("./Upload ");
// Get the file name
String fileName = System. IO. Path. GetFileName (
Uploader. PostedFile. FileName );
String destPath = System. IO. Path. Combine (destDir, fileName );
// Save it to the server
Uploader. PostedFile. SaveAs (destPath );
LblStatus. Text + = "Thanks for submitting your file .";
// Display the content. If the file is too large, do not use ReadToEnd (),
StreamReader r = new StreamReader (Uploader. PostedFile. InputStream );
LblStatus. Text + = r. ReadToEnd ();
R. Close ();
}
}
Catch (Exception err)
{
LblStatus. Text = err. Message;
}
}
}
We can create a globally unique identifier.
Private string GetFileName ()
{
// Create a unique filename.
String fileName = @ "Log \ user." +
Guid. NewGuid (). ToString ();
// Put the file in the current web application path.
Return Path. Combine (Request. PhysicalApplicationPath, fileName );
}