C# 将文件保存到服务器上的文件夹而不是本地
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17838914/
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
C# save files to folder on server instead of local
提问by Rob Carroll
The project is an MVC 4 C# based web application.
该项目是一个基于 MVC 4 C# 的 Web 应用程序。
I'm currently working locally and would like to have the ability to upload a file to my locally running application in debug mode and have the file saved to the web server instead of the my local folder.
我目前在本地工作,希望能够在调试模式下将文件上传到我本地运行的应用程序,并将文件保存到 Web 服务器而不是我的本地文件夹。
Currently we are using:
目前我们正在使用:
if (!System.IO.File.Exists(Server.MapPath(PicturePath)))
{
file.SaveAs(Server.MapPath(PicturePath));
}
How can we leverage this code to save to a webserver directly. Is that even possible?
我们如何利用此代码直接保存到网络服务器。这甚至可能吗?
Right now the file gets saved to my local path and the path is stored in the database, we then have to upload the files to the webserver manually.
现在文件被保存到我的本地路径并且路径存储在数据库中,然后我们必须手动将文件上传到网络服务器。
采纳答案by musefan
The SaveAs
function takes a filename and will save the file to any path you give it, providing the following conditions are met:
该SaveAs
函数采用文件名并将文件保存到您提供的任何路径,前提是满足以下条件:
- You local machine can access the filepath
- Your local account has the correct privileges to write to the filepath
- 您的本地机器可以访问文件路径
- 您的本地帐户具有写入文件路径的正确权限
I would suggest you have a web.config setting that can be checked when running your code. Then you can decide if to use Server.MapPath
or an absolute path instead.
我建议你有一个可以在运行代码时检查的 web.config 设置。然后您可以决定是使用Server.MapPath
还是绝对路径。
For example, in "debug" more (running locally) you might have the following settings:
例如,在“调试”更多(本地运行)中,您可能具有以下设置:
<appSettings>
<add key="RunningLocal" value="true" />
<add key="ServerFilePath" value="\\MyServer\SomePath\" />
</appSettings>
and in "live" mode:
并在“实时”模式下:
<appSettings>
<add key="RunningLocal" value="false" />
<add key="ServerFilePath" value="NOT USED" />
</appSettings>
Then your code may look something like this:
那么您的代码可能如下所示:
bool runningLocal = GetFromConfig();
bool serverFilePath = GetFromConfig();
string filePath;
if(runningLocal)
filePath = serverFilePath;
else
filePath = Server.MapPath(PicturePath);
if (!System.IO.File.Exists(filePath ))
{
file.SaveAs(filePath );
}