2011-03-11 100 views
5

我試圖從共享點將文件檢索到本地硬盤。將SPFile保存到本地硬盤

這裏是我的代碼:

SPFile file = web.GetFile("http://localhost/Basics.pptx");     
byte[] data = file.OpenBinary(); 
FileStream fs = new FileStream(@"C:\Users\krg\Desktop\xyz.pptx",FileMode.Create,FileAccess.Write); 

BinaryWriter w = new BinaryWriter(fs);    
w.Write(data, 0, (int)file.Length);    
w.Close();    
fs.Close(); 

當我試圖打開文件時,它顯示爲損壞的文件。

原始文件大小爲186kb,下載後文件大小爲191kb。

什麼是從sharepoint下載文件的解決方案..?

回答

4

你不需要的BinaryWriter:

int size = 10 * 1024; 
using (Stream stream = file.OpenBinaryStream()) 
{ 
    using (FileStream fs = new FileStream(@"C:\Users\krg\Desktop\xyz.pptx", FileMode.Create, FileAccess.Write)) 
    { 
    byte[] buffer = new byte[size]; 
    int bytesRead; 
    while((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) 
    { 
     fs.Write(buffer, 0, bytesRead); 
    } 
    } 
} 
+2

如果該文件不是10 * 1024的偶數倍,則最後一次調用fs.Write會在文件末尾寫入垃圾字符。另外,寫入文件的文件大小將始終爲10 * 1024的倍數。請參閱Igauthier的更正版本。 – 2013-06-08 09:52:11

+0

謝謝。修復了我的回答 – Stefan 2014-03-19 08:12:19

12

只是爲了這個答案有點貢獻。最好檢查每個塊中讀取的字節數,以便寫入的流將成爲從SharePoint讀取的流的確切副本。 請參閱下面的更正。

int size = 10 * 1024; 
using (Stream stream = file.OpenBinaryStream()) 
{ 
using (FileStream fs = new FileStream(@"C:\Users\krg\Desktop\xyz.pptx", FileMode.Create, FileAccess.Write)) 
{ 
    byte[] buffer = new byte[size]; 
    int nbBytesRead =0; 
    while((nbBytesRead=stream.Read(buffer, 0, buffer.Length)) > 0) 
    { 
     fs.Write(buffer, 0, nBytesRead); 
    } 
} 
} 
+0

除非超過6個字符,否則我無法提供編輯。但在這個答案中有一個錯字'nBytesRead'應該是'nbBytesRead' – Mattisdada 2016-05-11 01:57:56