找不到sharepoint中的C#异常处理

时间:2013-12-30 10:10:47

标签: c# file sharepoint http-status-code-404 http-response-codes

这是我的代码:

   try{
       using (Microsoft.SharePoint.Client.ClientContext context = new Microsoft.SharePoint.Client.ClientContext(siteURL))
            {
                #region get the name of the file and check if the  file is valid

                context.AuthenticationMode = Microsoft.SharePoint.Client.ClientAuthenticationMode.FormsAuthentication;
                Microsoft.SharePoint.Client.FormsAuthenticationLoginInfo formsAuthInfo = new
                Microsoft.SharePoint.Client.FormsAuthenticationLoginInfo(UserName, Password);
                context.FormsAuthenticationLoginInfo = formsAuthInfo;
                File file = context.Web.GetFileByServerRelativeUrl(relativeFilePath);
                context.Load(file);
                context.ExecuteQuery();
                documentName = Convert.ToString(file.Name);                    
                #endregion

    }
    }
    catch(ServerUnauthorizedAccessexception ex)
    {

    }
    catch(WebException We)
    {

    }

    catch (ServerException s)
    {

if (s.Message == "File Not Found.")
{
    htmlClose = "<html><title>Cannot Get File</title><body><script type='text/javascript'>alert('The specified file is not found in Sharepoint.');self.close();</script></body></html>";
}
else
{
    htmlClose = "<html><title>Cannot Get File</title><body><script type='text/javascript'>alert('Unable to retrieve file.Please contact your administrator');self.close();</script></body></html>";
}
httpContext.Response.Write(htmlClose);
httpContext.Response.Flush();
    }

我想知道我做了什么 确保在sharepoint中找不到文件是正确的。

基本上我使用了异常消息来验证在sharepoint中是否找不到文件。 抛出异常的代码是:

    context.Load(file);
    context.ExecuteQuery();

我使用了不同的catch块来捕获:ServerUnauthorizedAccessexception,WebException和服务器异常。 我发现Server异常是用于确保在sharepoint中找不到文件的异常。 在我完成的那部分代码中

   catch (ServerException s)
   {

   if (s.Message == "File Not Found.")
   {
   htmlClose = "<html><title>Cannot Get File</title><body><script type='text/javascript'>alert('The specified file is not found in Sharepoint.');self.close();</script></body></html>";
   }
   else
   {
   htmlClose = "<html><title>Cannot Get File</title><body><script type='text/javascript'>alert('Unable to retrieve file.Please contact your administrator');self.close();</script></body></html>";
   }
   httpContext.Response.Write(htmlClose);
   httpContext.Response.Flush();
   }

1 个答案:

答案 0 :(得分:2)

获得WebException后,您可以使用Response属性访问来自Web服务器的响应(如果有)。然后,您可以将其强制转换为适当的子类,并检查错误代码:

catch (WebException e)
{
    var response = (HttpWebResponse) e.Response;
    if (response != null && response.StatusCode == HttpStatusCode.NotFound)
    {
        // You got a 404...
    }
}