救命! WebClient.UploadFile()在将文件上载到sharepoint时抛出异常

时间:2010-05-19 12:30:33

标签: c# winforms exception sharepoint-2007 file-upload

在我的应用程序中,我将文件上传到sharepoint 2007.我正在使用

using (WebClient webClient = new WebClient())
{
 webClient.Credentials = new NetworkCredential(userName, password);
 webClient.Headers.Add("Content-Type", "application/x-vermeer-urlencoded");
 webClient.Headers.Add("X-Vermeer-Content-Type", "application/x-vermeer-urlencoded");
 String result = Encoding.UTF8.GetString(webClient.UploadData(webUrl + "/_vti_bin/_vti_aut/author.dll","POST", data.ToArray()));
}

代码正在成功运行..但对于某些文件,它会抛出异常

  

基础连接已关闭:   连接已关闭   不料。在   System.Net.WebClient.UploadDataInternal(URI   地址,字符串方法,字节[]数据,   WebRequest类和放大器;请求)   System.Net.WebClient.UploadData(URI   地址,字符串方法,字节[]数据)
  在   System.Net.WebClient.UploadData(字符串   地址,字符串方法,字节[]数据)

任何想法我做错了什么?

我正在使用VS-2008 2.0

1 个答案:

答案 0 :(得分:1)

这是我用来同时上传包含元数据的文档的函数:

public static bool Upload(string webUrl, string documentName, byte[] bytes, Dictionary<string, object> metaInfo, out string result)
{
    string putOption = "overwrite,createdir,migrationsemantics";  // see http://msdn2.microsoft.com/en-us/library/ms455325.aspx 
    string comment = null;
    bool keepCheckedOut = false; 
    string method = "method=put+document%3a12.0.4518.1016&service_name=%2f&document=[document_name={0};meta_info=[{1}]]&put_option={2}&comment={3}&keep_checked_out={4}\n"; 
    method = String.Format(method, documentName, EncodeMetaInfo(metaInfo), putOption, HttpUtility.UrlEncode(comment), keepCheckedOut.ToString().ToLower()); 
    List<byte> data = new List<byte>();
    data.AddRange(Encoding.UTF8.GetBytes(method));
    data.AddRange(bytes); 
    try 
    { 
        using (WebClient webClient = new WebClient()) 
        { 
            webClient.Credentials = CredentialCache.DefaultCredentials; 
            webClient.Headers.Add("Content-Type", "application/x-vermeer-urlencoded");
            webClient.Headers.Add("X-Vermeer-Content-Type", "application/x-vermeer-urlencoded");
            result = Encoding.UTF8.GetString(webClient.UploadData(webUrl + "/_vti_bin/_vti_aut/author.dll", "POST", data.ToArray()));
            if (result.IndexOf("\n<p>message=successfully") < 0)   
                throw new Exception(result);
        } 
    }
    catch (Exception ex)
    { 
        result = ex.Message; 
        return false; 
    }

    return true;
}

这是谷歌的某个地方,但唉,我是一个顽皮的程序员,并没有在我的评论中把链接。遗憾...