简体   繁体   中英

Confirm a Folder Exists on a Web Server from a C# Desktop Application

I am trying to confirm that a folder has been uploaded to my Website folder so that it can be accessed by a Desktop application. I keep getting an error that states that there is a URI format error on the connection string. There is no shortage of 'solutions' on the general inte.net but I cannot get anything to work, even ones on this site (of which I am a member for many years). Forward slashes, back slashes, no slashes... on and on. I am thoroughly confused. The following seems to be a simple and correct code, but it does not work either even though it is a direct copy of a solution that was offered as correct. The passed string 's' is the name of the folder I am trying to look for, A polite simple answer, perhaps with an example. is my desperate request. Thank You.

private bool CheckFiles(string s)
{
    bool exists = System.IO.Directory.Exists(@"\\\\http:/www.myserver.com/sites/"+ s);
    return exists;
}

System.IO.Directory.Exists checks for a directory in the file system. The address that is provided as a parameter is a http-URL that is not supported by file system access.

If you want to check for the presence of the folder on a webserver, you need to use a http client to "talk" to the server. Send a GET or HEAD request to the URL. If this returns a 200 (ok), the folder exists, if it returns 404 (not found), it doesn't.

As you are using .NET Framework 4.5 (or 4.0), you can use WebClient or better HttpClient for this. The following should give you an idea of how to check for the folder:

using (var http = new HttpClient())
{
  using (var req = new HttpWebRequest(HttpMethod.Head, "https://..."))
  {
    using (var resp = http.Send(req))
    {
      // This is a very broad condition; 
      // you can also check the StatusCode property against HttpStatusCode.NotFound
      return resp.IsSuccessStatusCode;
    }
  }
}

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