How to set physical path to upload file in Asp.Net?

I want to upload a file on a physical path, for example . E:\Project\Folders

I got the code below by doing a network search.

//check to make sure a file is selected
if (FileUpload1.HasFile)
{
    //create the path to save the file to
    string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);
    //save the file to our local path
    FileUpload1.SaveAs(fileName);
}

But in this I want to give my physical path, as I mentioned above. How to do it?

+3
source share
2 answers

Server.MapPath("~/Files")returns the absolute path based on the folder relative to your application. The host ~/tells ASP.Net to look at the root of your application.

To use a folder outside the application:

//check to make sure a file is selected
if (FileUpload1.HasFile)
{
    //create the path to save the file to
    string fileName = Path.Combine(@"E:\Project\Folders", FileUpload1.FileName);
    //save the file to our local path
    FileUpload1.SaveAs(fileName);
}

Of course, you will not hardcode the path in the production application, but this should save the file using the absolute path you described.

As for the search for the file after saving it (in the comments):

if (FileUpload1.HasFile)
{
    string fileName = Path.Combine(@"E:\Project\Folders", FileUpload1.FileName);
    FileUpload1.SaveAs(fileName);

    FileInfo fileToDownload = new FileInfo( filename ); 

    if (fileToDownload.Exists){ 
        Process.Start(fileToDownload.FullName);
    }
    else { 
        MessageBox("File Not Saved!"); 
        return; 
    }
}
+7

All Articles