asp.net upload file in csharp

One way to handle file uploads in ASP.NET is through the use of the FileUpload control in Web Forms. Here's an example of how to use this control to upload a file in C#:

  1. Add a FileUpload control to your Web Forms page:
<asp:FileUpload ID="fileUploadControl" runat="server" />
57 chars
2 lines
  1. In the code-behind file, add a button click event handler to handle the file upload:
main.cs
protected void uploadButton_Click(object sender, EventArgs e)
{
    // Check if a file was actually selected
    if (fileUploadControl.HasFile)
    {
        try
        {
            // Get the filename and extension
            string fileName = fileUploadControl.FileName;
            string fileExtension = Path.GetExtension(fileName);

            // Generate a unique filename to prevent overwriting existing files
            string uniqueFileName = Guid.NewGuid().ToString("N") + fileExtension;

            // Save the file to a specified location
            string savePath = Server.MapPath("~/Uploads/") + uniqueFileName;
            fileUploadControl.SaveAs(savePath);

            // Display success message
            resultLabel.Text = "File uploaded successfully!";
        }
        catch (Exception ex)
        {
            // Display error message
            resultLabel.Text = "Error uploading file: " + ex.Message;
        }
    }
    else
    {
        // Display error message if no file was selected
        resultLabel.Text = "Please select a file to upload.";
    }
}
1098 chars
34 lines
  1. When the user clicks the button, the file is uploaded to the server and saved to the specified location. The filename is also changed to a unique value to prevent overwriting existing files. Finally, a success or error message is displayed to the user indicating the result of the upload.

Note: Don't forget to add appropriate validation to check the size and type of the uploaded file, and to secure the upload location to prevent unauthorized access.

gistlibby LogSnag