Rob
Rob

Reputation: 3574

check if folder exists c# webrequest

I'm using this to create a folder in an existing sharepoint location. Is there a way to check if a folder exists before creation instead of using try/catch to figure out of this method fails and then assume the folder exists? I've checked the webrequest methods, but there is no such this as a check.

try
{
    HttpWebRequest request = (System.Net.HttpWebRequest)HttpWebRequest.Create("https://site.sharepoint.com/files/"+foldername);
    request.Credentials = CredentialCache.DefaultCredentials;
    request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
    request.Method = "MKCOL";
    HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
    response.Close();
}
catch (Exception ex) 
{ 
    //if this piece fails the folder exists already 
} 

Upvotes: 1

Views: 5030

Answers (2)

Sigar Dave
Sigar Dave

Reputation: 2654

public void CheckWebFoldersExist()
 {
  try
   {
    WebClient client = new WebClient();
    client.Credentials = CredentialCache.DefaultCredentials;
    // Create a request for the URL.         
    WebRequest request = WebRequest.Create("myAddress");

    // If required by the server, set the credentials.
    request.Credentials = CredentialCache.DefaultCredentials;

    // Get the response.
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    //check response status
    if (string.Compare(response.StatusDescription, "OK", true) == 0)
    { 
       //URL exists so that means folder exists
    }
    else
    {
        //URL does not exist so that means folder does not exist
    }
  }
   catch (Exception error)
   {
      //error catching
   }

}

Upvotes: 2

Damith
Damith

Reputation: 63065

you can use SPWeb.GetFolder Method

private bool CheckFolderExists(SPWeb parentWeb, string folderName) {
    SPFolder folder = parentWeb.GetFolder(folderName);
    return folder.Exists;
}

ref : http://mundeep.wordpress.com/2009/02/24/checking-if-a-spfolder-exists/

Upvotes: 2

Related Questions