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

本文关键字:文件 路径 设置 Asp Net | 更新日期: 2023-09-27 18:33:20

我想在物理路径中上传文件,例如 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);
}

但在这方面,我想给出我上面提到的我的物理路径。怎么做?

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

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

嗯,

您可以使用 VirtualPathUtility 来完成此操作

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