C# 将文件保存到服务器上的文件夹而不是本地 [英] C# save files to folder on server instead of local

查看:51
本文介绍了C# 将文件保存到服务器上的文件夹而不是本地的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该项目是一个基于 MVC 4 C# 的 Web 应用程序.

The project is an MVC 4 C# based web application.

我目前在本地工作,希望能够在调试模式下将文件上传到我本地运行的应用程序,并将文件保存到 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.

目前我们正在使用:

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.

推荐答案

SaveAs 函数接受一个文件名并将文件保存到您给它的任何路径,前提是满足以下条件:

The SaveAs function takes a filename and will save the file to any path you give it, providing the following conditions are met:

  • 您的本地机器可以访问文件路径
  • 您的本地帐户具有写入文件路径的正确权限

我建议您有一个可以在运行代码时检查的 web.config 设置.然后您可以决定是使用 Server.MapPath 还是使用绝对路径.

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.

例如,在调试"中模式(在本地运行)您可能有以下设置:

For example, in "debug" mode (running locally) you might have the following settings:

<appSettings>
    <add key="RunningLocal" value="true" />
    <add key="ServerFilePath" value="\\MyServer\SomePath\" />
</appSettings>

并在直播"中模式:

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

这篇关于C# 将文件保存到服务器上的文件夹而不是本地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆