Downloading files from a SharePoint document library to file system

Here's the code to download files of a certain type (in the example, I set it to find documents in the list with the .doc extension) from a document library to your hard drive.

    SPWeb mySite = SPContext.Current.Web;
    mySite.AllowUnsafeUpdates = true;
    SPList oList = mySite.Lists[<ListName>];
    SPQuery oQuery = new SPQuery();
    oQuery.Query = "<Where><Eq><FieldRef Name='DocIcon'/><Value Type='Computed'>doc</Value></Eq></Where>";
    SPListItemCollection listItems = oList.GetItems(oQuery);

    for (int i = 0; i < listItems.Count; i++) {
            SPListItem item = listItems[i];

            // copy this file to the temp folder
            byte[] binfile = item.File.OpenBinary();

            FileStream fs = new FileStream("C:\\Temp\\" + item["Name"], FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(binfile);
            bw.Close();
    }

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.