Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving SPFile to local hard disk

I am trying to retrieve the file from sharepoint to local hard disk.

Here is my code:

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();

When I am trying to open that file, it is showing as a corrupted file.

The original file size is 186kb, after download the file size is 191kb.

What is the solution to download the file from sharepoint..?

like image 782
Ramesh.kbvr Avatar asked Mar 11 '11 07:03

Ramesh.kbvr


2 Answers

Just a little contribution to this answer. It's better to check the number of bytes read in each bloc so that the stream written will be the exact replicat of the stream read from SharePoint. See correction below.

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);
   }
 }
}
like image 161
tgauthier Avatar answered Oct 22 '22 19:10

tgauthier


You do not need the 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);
    }
  }
}
like image 5
Stefan Avatar answered Oct 22 '22 18:10

Stefan