检查服务器上是否存在文件以进行读写

Check if file exist on server to read and write

我正在尝试使用 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);
use System.IO.File.Exists() 

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

一种简单的方法是使用 WebClient.DownloadFile() 尝试从您正在使用的 url 下载文件。如果抛出 WebException 并且 HTTP 错误为 404 未找到文件,则服务器上不存在该文件(或者您无权访问它)。

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

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