user2387900
user2387900

Reputation: 215

Finding the exact path of the file

I am using the fileUpload control. When I upload the file, I want to find the exact location of the file.

I tried using:

  1. string fname= Server.MapPath(FileUpload2.FileName);
  2. string fname= FileUpload2.FileName;
  3. string fname= FileUpload2.PostedFile.FileName;

Numbers 2 & 3 gave me the name of the file. Number 1 gave me the the path of my website location. I do not know what is the difference between 2 and 3, why both gave me same results.

I read somewhere, that you cannot get the path. Is it true? If not, what code should I use?

Upvotes: 2

Views: 480

Answers (1)

Josh
Josh

Reputation: 44906

There is no actual file path because a file uploaded to the server is simply held in memory.

The FileUpload control is just a wrapper around an HttpPostedFile instance, which itself is basically just a wrapper around an InputStream.

It's up to you to actually save the file somewhere. Until then it doesn't exist in any physical location.

The FileName property simply corresponds to the filename from the client's machine, minus the path. It has no correlation to anything on the server's file system.

There are a couple of different ways you can deal with the file.

Save The File To Disk:

The FileUpload control provides a SaveAs method that will allow you to save the file locally, or some UNC that you have access to.

FileUpload2.SaveAs("C:\\Temp\\" + FileUpload2.FileName);

Process The File In Memory:

Since you have access to the FileContent, you could simply manipulate and process the file directly. Assuming you know what type of file it is (txt, pdf, csv, etc...)

using (var sr = new StreamReader(FileUpload2.FileContent)) 
{
    while ((var line = sr.ReadLine()) != null) 
    {
        //Do something with 'line'
    }
}

Upvotes: 1

Related Questions