2012-11-05 104 views
1

我正在使用它在現有的共享點位置創建一個文件夾。有沒有辦法在創建之前檢查文件夾是否存在,而不是使用try/catch來判斷此方法失敗,然後假定該文件夾存在? 我已經檢查了webrequest方法,但沒有這樣的支票。檢查文件夾是否存在c#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 
} 
+0

可你只是提出一個要求通過'HttpWebRequest'文件夾,看看是否存在(或得到404 )? –

回答

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 
    } 

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

+0

但即使在返回true之後,您仍然可以獲得例外,包括FileNotFound。這不是併發安全的。 –

+0

我沒有使用SharePoint服務器,所以很不幸,這對我來說不是解決方案。 – Rob

相關問題