检查文件夹是否存在c#webrequest

时间:2012-11-05 12:54:06

标签: c# sharepoint httpwebrequest

我正在使用它在现有的sharepoint位置创建一个文件夹。有没有办法在创建之前检查文件夹是否存在而不是使用try / catch来解决此方法失败然后假设该文件夹存在? 我已经检查了webrequest方法,但没有这样的检查。

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 
} 

2 个答案:

答案 0 :(得分:2)

您可以使用SPWeb.GetFolder Method

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

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

答案 1 :(得分:1)

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
   }

}