将SPFile保存到本地硬盘

时间:2011-03-11 07:21:28

标签: c# asp.net sharepoint sharepoint-2010

我正在尝试将文件从sharepoint检索到本地硬盘。

这是我的代码:

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下载文件有什么解决方案..?

2 个答案:

答案 0 :(得分:13)

对这个答案只做了一点贡献。最好检查每个bloc中读取的字节数,以便写入的流将是从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);
   }
 }
}

答案 1 :(得分: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);
    }
  }
}