2011-03-11 95 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