2016-10-07 50 views
0

我無法訪問Sharepoint服務器,只能像網頁上的標準用戶一樣。我可以在那裏手動上傳我的文檔。我試圖通過C#解決它,我完成了來自網絡示例的任何代碼。我們的Sharepoint是2007年。我的代碼運行沒有任何錯誤。我把那裏的控制文本,看看它是否繼續。所有運行良好,但Sharepoint頁面沒有任何反應,沒有文件上傳。我不知道爲什麼它什麼也不做:)如何將文件上傳到sharepoint 2007 C#

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.IO; 
using System.Net; 



namespace Sharepoint 
{ 
    class Program 
{ 
     public static void CopyStream(Stream read, Stream write) 
     { 



      int len; byte[] temp = new byte[1024]; 

      while ((len = read.Read(temp, 0, temp.Length)) > 0) 
      { 
       write.Write(temp, 0, len); 
      /// Console.WriteLine("test"); 
      } 



     } 



     static void Main(string[] args) 
     { 




      Uri destUri = new Uri("http://gaja/mBreSKCZ/mreports/sales/reportysales/Test_new.txt"); 
      using (FileStream inStream = File.OpenRead(@"C:\Users\TK20382\Test_new.txt")) 
      { 
       WebRequest req = WebRequest.Create(destUri); 
       req.Method = "PUT"; 
       req.Credentials = CredentialCache.DefaultCredentials; // assuming windows Auth 
       Console.WriteLine("test"); 
       Console.ReadKey(); 
       using (Stream outStream = req.GetRequestStream()) 
       { 
        CopyStream(inStream, outStream); 
       } 

      } 



     } 


    } 
} 

回答

0

你缺少HttpWebRequest.GetResponse Method基本上調用PUT請求。此外,如果您的目標的.NET Framework> = 2.0版本,然後CopyStream方法可以被省略,並且該行:

CopyStream(inStream, outStream); 

替換爲:

inStream.CopyTo(outStream); 

修改版

public static string UploadFile(string targetUrl,ICredentials credentials, string sourcePath) 
{ 
     var request = WebRequest.Create(targetUrl); 
     request.Method = "PUT"; 
     request.Credentials = credentials; 
     using (var fileStream = File.OpenRead(sourcePath)) 
     using (var requestStream = request.GetRequestStream()) 
     { 
      fileStream.CopyTo(requestStream); 
     } 
     using (var response = request.GetResponse()) 
     using (var reader = new StreamReader(response.GetResponseStream())) 
     { 
      return reader.ReadToEnd(); 
     } 
} 

用法

UploadFile("https://contoso.intranet.com/documents/guide.docx", CredentialCache.DefaultCredentials, @"D:\guide.docx"); 

或者WebClient.UploadFile Method可以利用如下圖所示:

public static void UploadFile(string targeUrl, ICredentials credentials, string fileName) 
{ 
    using (var client = new WebClient()) 
    { 
     client.Credentials = credentials; 
     client.UploadFile(targeUrl, "PUT", fileName); 
    } 
} 
+1

感謝您的幫助,二者均在正常工作。托馬斯 –

相關問題