C# 使用 HttpPostedFileBase.SaveAs 在物理路径中保存上传的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16832070/
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-10 07:53:49  来源:igfitidea点击:

Saving an uploaded file with HttpPostedFileBase.SaveAs in a physical path

c#asp.netasp.net-mvcrazorio

提问by Lamloumi2

I'd like to save an uploaded file to a physical path by the method HttpPostedFileBase.SaveAs().

我想通过方法将上传的文件保存到物理路径HttpPostedFileBase.SaveAs()

When I choose a physical path, an exception appears indicates that the path must be virtual.

当我选择物理路径时,出现异常表示路径必须是虚拟的。

 var fileName = Path.GetFileName(fileurl.FileName);
 var path = "C:/Projets" + fileName;
 fileurl.SaveAs(Server.MapPath(path));

How can I change my code to be able to save the file every where I want?

如何更改我的代码以便能够将文件保存在我想要的任何位置?

采纳答案by Darin Dimitrov

The Server.MapPathworks only with physical locations that are part of the website. If you want to save the file outside you could use the following:

Server.MapPath只与网站的部分物理位置工作。如果要将文件保存在外部,可以使用以下命令:

var fileName = Path.GetFileName(fileurl.FileName);
fileurl.SaveAs(Path.Combine(@"c:\projects", fileName));

Make sure though that the account under which your application pool is executing is granted write permissions to this folder.

请确保您的应用程序池所使用的帐户被授予对此文件夹的写入权限。

回答by Kindzoku

Server.MapPath is for virtual path. You can try to use Path.GetFullPath(path).

Server.MapPath 用于虚拟路径。您可以尝试使用 Path.GetFullPath(path)。