Samy Sammour
Samy Sammour

Reputation: 2465

Copy file from SharePoint 2010 to local path c#

I am developing a SharePoint 2010 application using VS2010 with C# and I need a code to copy File from the Shared Document to a local Folder.

I wrote this code:

var dest = @"C:\location";
var source = @"http://server1/sites/PrDB/";
var fileName = "sql.txt";

using (SPSite site = new SPSite(source))
{
    using (SPWeb web = site.OpenWeb())
    {
            SPFile file = web.GetFile("Shared%20Documents/" + fileName);
            byte[] b = file.OpenBinary();
            FileStream fs = new FileStream(dest + "\\" + file.Name, FileMode.Create, FileAccess.ReadWrite);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(b);
            bw.Close();
    }
}

I am receiving an Error on the line: file.OpenBinary();

Cannot open file "Shared Documents/sql.txt".

Anybody know why? And how can I fix it?

Upvotes: 0

Views: 4504

Answers (3)

Samy Sammour
Samy Sammour

Reputation: 2465

I found the solution after hours of trying, the problem was with reading the file using the SPWeb:

    var dest = @"C:\location";
    var source = @"http://server1/sites/PrDB/";
    using (SPSite site = new SPSite(source))
         {
              using (SPWeb web = site.OpenWeb())
              {
                    SPFolder myfolder = web.GetFolder("Shared Documents");
                    SPFile file = myfolder.Files[fileName];
                    byte[] b = file.OpenBinary();
                    string fullPath =destination + "\\" + file.Name;
                    FileStream fs = new FileStream(fullPath, FileMode.Create, FileAccess.ReadWrite);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(b);
                    bw.Close();
                    }
                }

Upvotes: 1

Vaibhav
Vaibhav

Reputation: 447

I know you are looking for code based solution. but in case you are open to chose OOTB solution then try this just one line of code attach it to href of anchor tag

  http://spsite/_layouts/download.aspx?SourceUrl=http://spsite/Documents/sample.docx

Upvotes: 0

love thakker
love thakker

Reputation: 470

To get the file you need to pass full url. Please try below code:

  var dest = @"C:\location";
    var source = @"http://server1/sites/PrDB/";
    var fileName = "sql.txt";

    using (SPSite site = new SPSite(source))
    {
        using (SPWeb web = site.OpenWeb())
        {
                SPFile file = web.GetFile(web.Url +"/Shared%20Documents/" + fileName);// here, this added web url
    if(file.Exists) 
        {
                byte[] b = file.OpenBinary();
                FileStream fs = new FileStream(dest + "\\" + file.Name, FileMode.Create, FileAccess.ReadWrite);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(b);
                bw.Close();
        }
    }
 }

Upvotes: 0

Related Questions