0

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)

Cyber Progs
  • 3,656
  • 3
  • 30
  • 39
TRI
  • 21
  • 1
  • 4
  • So you've already found an approach that gets you the full path. Why are you trying to use something else for the value you store in the DB? Your question doesn't make sense as stated. – JLRishe Aug 11 '17 at 17:02

2 Answers2

0

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.

JoeMc
  • 26
  • 1
  • 3
  • Thanks for the edit @Michelle, I am new to this and am learning all the standards and best practices. – JoeMc Aug 16 '17 at 21:14
0

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.

BHigzz
  • 45
  • 1
  • 5