Hosemeyer Hosemeyer - 1 year ago 80
ASP.NET (C#) Question

How to correctly use the ASP.NET FileUpload control

I'm trying to use the FileUpload control in ASP.NET

Here's my current namespace setup:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

And within my class, I'm just using:

FileUpload fileUpload = new FileUpload();

However, none of the attributes that are normally part of FileUpload seem to be available... such as .HasFile. I'm attempting to make the Button click method in the code behind, I have noticed that most of the usage of .HasFile is in the code in front, however it was my understanding that this shouldn't matter.

Does anyone know why?

Answer Source

ASP.NET controls should rather be placed in aspx markup file. That is the preferred way of working with them. So add FileUpload control to your page. Make sure it has all required attributes including ID and runat:

<asp:FileUpload ID="FileUpload1" runat="server" />

Instance of FileUpload1 will be automatically created in auto-generated/updated *.designer.cs file which is a partial class for your page. You usually do not have to care about what's in it, just assume that any control on an aspx page is automatically instantiated.

Add a button that will do the post back:

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

Then go to your *.aspx.cs file where you have your code and add button click handler. In C# it looks like this:

protected void Button1_Click(object sender, EventArgs e)
  if (this.FileUpload1.HasFile)
    this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);

And that's it. All should work as expected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download