0

我想在另一个子域的子域中检查文件,在 sub1 中的文件,我想在 sub2 中检查此文件。

sub1 中的地址文件:sub1.mysite.com/img/10.jpg

 Server.MapPath(@"~/img/10.jpg");

我已经在 sub2 中检查了这个文件,所以我使用了这个代码:一些代码在这里

if (System.IO.File.Exists(Server.MapPath(@"~/img/10.jpg")))
{
   ...             
}

if (System.IO.File.Exists("http://sub1.mysite.com/img/10.jpg"))
{
   ...             
}

但它不工作。请帮我。

4

2 回答 2

1

使用 HttpWebRequest 发送资源请求并检查响应。

就像是:

bool fileExists = false;
try
 {
      HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create("http://sub1.mysite.com/img/10.jpg");
      using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
      {
           fileExists = (response.StatusCode == HttpStatusCode.OK);
      }
 }
 catch
 {
 }
于 2013-03-12T21:43:10.070 回答
1

您必须使用HttpWebRequest通过 HTTP 访问它。您可以创建一个实用方法来执行此操作,例如:

public static bool CheckExists(string url)
{
   Uri uri = new Uri(url);
   if (uri.IsFile) // File is local
      return System.IO.File.Exists(uri.LocalPath);

   try
   {
      HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
      request.Method = "HEAD"; // No need to download the whole thing
      HttpWebResponse response = request.GetResponse() as HttpWebResponse;
      return (response.StatusCode == HttpStatusCode.OK); // Return true if the file exists
   }
   catch
   {
      return false; // URL does not exist
   }
}

然后这样称呼它:

if(CheckExists("http://sub1.mysite.com/img/10.jpg"))
{
   ...
}
于 2013-03-12T21:44:29.013 回答