如何在Asp.Net中设置上传文件的物理路径?

时间:2012-05-07 09:47:33

标签: c# asp.net visual-studio-2010 file-upload

我想以物理路径上传文件,例如 E:\Project\Folders

我在网上搜索了以下代码。

//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);
}

但在那里,我想像上面提到的那样给出我的物理路径。怎么做?

3 个答案:

答案 0 :(得分:7)

Server.MapPath("~/Files")根据相对于您的应用程序的文件夹返回绝对路径。领先的~/告诉ASP.Net查看应用程序的根目录。

要使用应用程序之外的文件夹:

//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);
}

当然,您不会在生产应用程序中硬编码路径,但这应该使用您描述的绝对路径保存文件。

关于在保存文件后定位文件(每条评论):

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; 
    }
}

答案 1 :(得分:2)

好吧,

您可以使用VirtualPathUtility

来完成此操作

答案 2 :(得分:0)

// Fileupload1 is ID of Upload file
if (Fileupload1.HasFile)
{
    // Take one variable 'save' for store Destination folder path with file name
    var save = Server.MapPath("~/Demo_Images/" + Fileupload1.FileName);
    Fileupload1.SaveAs(save);
}