Server.MapPath(FileUploadControl.FileName) not returning full path + file name

1.4k Views Asked by At

I'm trying to save the path of a file (with the file name included) to a database column. Imagine my project directory is called Project, there I have a folder called Attachments.

In my code I'm doing this to upload the file to the location I choose:

string filename = Path.GetFileName(FileUploadControl.FileName);
                    FileUploadControl.SaveAs(Server.MapPath("~/Attachments/") + filename);

This works great and if I open that folder the file is there! Now my problem is with saving the path+filename to database column. I'm currently using Server.MapPath(FileUploadControl.FileName), but when I check in database column it only saves the path string until my Project, like C:\[somepath]\Project\. So it's missing the Attachments folder and the file name. Any help? I already read a lot of topics about FileUploadControl here but nothing helped me. I'm using ASP.NET C# and the column type saving that information is in varchar(MAX)

2

There are 2 best solutions below

1
JoeMc On

Use Path.GetFileName instead of Server.MapPath to get the file name to store in the DB.

Note that storing the full path in the DB is not recommended. It has been my experience that storing just the portion of the path that is relevant is what you need.

if you are storing files in the path below:

C:\Application\Files\Documents\20170811\Myfile.txt

Then only store the relevant portion in the DB:

\Files\Documents\20170811\Myfile.txt

Put the C:\Application portion in your application's config file in order to obtain/build the physical path. Using this method, if you move the files to another drive (D:), all you need to do is change the configuration. Otherwise you would have to update every file name/path you have stored in the DB.

0
BHigzz On

The only reliable way I have found to get paths as you mentioned would be:

var inputFileDirectory = HttpContext.Current.Server.MapPath("~/Attachments/");

var fileName = System.IO.Path.GetFileName(fileUploader.PostedFile.FileName);

inputFileDirectory += fileName;

This methods works for all browsers, as IE and Edge will save the PostedFile.FileName as a fully qualified path, and others will just save the file name.