【问题标题】:Check if file exist on server to read and write检查服务器上是否存在要读写的文件
【发布时间】:2017-08-04 05:26:14
【问题描述】:

我正在尝试使用 System.Web; 从 winform 桌面应用程序读取和写入位于服务器上的文本文档。首先需要检查文件是否存在。不知道为什么,但是 System.Web 不起作用,它被添加为 System.Web 的引用

string siteDir = "http://www.site.info/doc.txt";

if (File.Exists(Server.MapPath(siteDir)));

System.Web.HttpContext相同

System.Web.HttpContext.Current.Server.MapPath(siteDir);

【问题讨论】:

  • 试试System.Web.Hosting.HostingEnvironment.MapPath(siteDir);
  • 这是桌面应用程序还是 Web 应用程序?您在其中放置了一个 winforms 标签,这表明这是一个桌面应用程序
  • 你需要引用程序集System.Web.dll
  • @StanleyS 你好。不,同样的结果,我使用 System.Web;也许我需要一些参考来使用它?
  • 解释“不起作用”。你得到一个编译错误?例外?代码运行但给出不同的结果?

标签: c# winforms server system.net system.web


【解决方案1】:

执行此操作的一种简单方法是使用WebClient.DownloadFile() 尝试从您正在使用的网址下载文件。如果抛出 WebException 并且 HTTP 错误是 404 File Not Found,则服务器上不存在该文件(或者您无权访问它)。

有关如何检测 404 错误的信息,请参阅:How to catch 404 WebException for WebClient.DownloadFileAsync

不幸的是,没有WebClient 方法可以简单地检查服务器上是否存在文件。

【讨论】:

  • 你好,谢谢,所以我这样做了 HttpWebResponse resp = ex.Response as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.NotFound) { //404 }
【解决方案2】:
use System.IO.File.Exists() 

if(System.IO.File.Exists([path of file]))
{
  // do something
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-29
    • 2012-05-15
    • 2012-10-01
    • 2012-06-13
    • 2014-06-27
    • 2011-11-16
    • 1970-01-01
    相关资源
    最近更新 更多