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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10479942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:00:30  来源:igfitidea点击:

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

c#asp.netvisual-studio-2010file-upload

提问by thevan

I want to upload a file in a physical path such as E:\Project\Folders.

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

I got the below code by searching in the net.

我通过在网上搜索得到了以下代码。

//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 that, I want to give my physical path as I mentioned above. How to do this?

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

采纳答案by Tim Medora

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

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

To use a folder outside of 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 wouldn't hardcode the path in a production application but this should save the file using the absolute path you described.

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

With regards to locating the file once you have saved it (per 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; 
    }
}

回答by Dimi Takis

Well,

好,

you can accomplish this by using the VirtualPathUtility

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

回答by heta naik

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