How can I use Server.MapPath to upload a file onto a server which is mapped on my computer

2.7k Views Asked by At

So far I know how to upload a file to a folder within my solution using the code below.

string root = HttpContext.Current.Server.MapPath("~/upload");

How can I save the file to a different location that is not within a solution i.e to a server location that is mapped to my pc.

string root = HttpContext.Current.Server.MapPath("/Z:/UploadFolder"); I have tried this but its not saving to the server so where I am going wrong?
3

There are 3 best solutions below

0
Ashkan Mobayen Khiabani On

You should use MapPath when you have a relative path and want to use the path to your project. for another path you don't need MapPath. just use it like this:

string root ="Z:\\UploadFolder";
0
Ctznkane525 On

You can map a virtual directory in IIS to the location you want to save to. For example, map a virtual directory of UploadFolder to z:\uploadfolder. Then, this will work:

string root = HttpContext.Current.Server.MapPath("~/upload");

Make sure you set permissions appropriately.

0
nithinmohantk On

Your logic seems to be confusing. Use Server.MapPath - Returns the physical file path that corresponds to the specified virtual path.

But you are passing Physical Location to Server.MapPath in the second statement, which fails the whole purpose of Server.MapPath.

string root = HttpContext.Current.Server.MapPath("/Z:/UploadFolder"); **INCORRECT**

Ideally, you would need to create a virtual directory mapping to "/Z:/UploadFolder" and name it as "upload".

string root = HttpContext.Current.Server.MapPath("~/upload");

NB: You would need to pass explicit credentials to access the network share from ASP.NET. The suggested approach is to use Identity impersonation, once it is done retry with the same logic.

<configuration>
  <system.web>
    <identity impersonate="true" />
  </system.web>
</configuration>