2017-03-14 97 views
0

我试图用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); 
+0

尝试'System.Web.Hosting.HostingEnvironment.MapPath(siteDir);' –

+0

这是一个桌面应用程序还是一个Web应用程序?你已经把一个winforms标签放在那里,这表明这是一个桌面应用程序 – Sparrow

+0

你需要引用程序集'System.Web.dll'。 –

回答

1

一个简单的方法来做到这一点是使用WebClient.DownloadFile()尝试从类似您正在使用的网址下载文件。如果抛出WebException并且HTTP错误为404 File Not Found,则该文件在服务器上不存在(或者您无权访问它)。

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

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

+0

你好,谢谢,所以我这样做了HttpWebResponse resp = ex.Response作为HttpWebResponse;如果(resp.StatusCode == HttpStatusCode.NotFound){// 404} – nikorio

-1
use System.IO.File.Exists() 

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

OP已经在问题中使用了'File.Exists'。 –

相关问题