简体   繁体   中英

check file in another subdomain

i want check file in subdomain at another subdomain, file in sub1 and i want check this file in sub2.

address file in sub1: sub1.mysite.com/img/10.jpg and

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

i have check this file in sub2, so i use this code: some code here it's

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

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

but its not working. please help me.

Use HttpWebRequest to send request for resource and inspect the response.

Something like:

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
 {
 }

You'll have to access it via HTTP using HttpWebRequest . You could create a utility method to do this, something like:

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

And then call it like:

if(CheckExists("http://sub1.mysite.com/img/10.jpg"))
{
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM