Link to home
Start Free TrialLog in
Avatar of ramadadi
ramadadi

asked on

How to download files from sharepoint using C#.Net

Hi Experts,
All my office files are present in share point server, i want to download these files to my local system using C# & Asp.net, how to do this, and Microsoft.sharepoint.dll will works in windows xp?
Avatar of Jamie McAllister
Jamie McAllister
Flag of Switzerland image

You don't necessarily need to use the SharePoint API to do this.

Here's an example I put together for Winforms;

http://www.the-north.com/sharepoint/post/2008/02/10/Accessing-Sharepoint-Documents-from-Winforms-via-HTTPS.aspx

Could be adapted to ASP.NET easily enough.

You could also use the SharePoint web services to get your hands on items.
You can't use the Sharepoint API (i.e. Sharepoint.dll and the rest) from anywhere except on the Sharepoint box itself. You can use the Web Services:

    http://ktskumar.wordpress.com/2009/03/08/download-document-from-sharepoint-library-using-webservice/

Or, if you have WebDav enabled, you should be able to retrieve the file by sending a Http request directly to the URL of the file in its document library.
ASKER CERTIFIED SOLUTION
Avatar of shrikantss
shrikantss
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ramadadi
ramadadi

ASKER

Hi carl_tawn,

Using sharepoint webservice i can able to copy single file to my local system, how to copy folder from sharepoint to the local system
As far as I am aware, you cannot directly copy a folder, you have to loop through the contents and download each file individually.
Hi Experts,

Below code works for me to download a single file from sharepoint, but i want to download all the file in folder, how to do this?

//"http://usdfw13as15:41090/_vti_bin/copy.asmx"
            string webURL = "http://usdfw13as15:41090";
            usdfw13as15.Copy copyService = new usdfw13as15.Copy();
            copyService.Url = webURL + "/_vti_bin/copy.asmx";
            copyService.Credentials = System.Net.CredentialCache.DefaultCredentials;

            string sourceUrl = "http://usdfw13as15:41090/sites/HB/HB/Asia%20Documents/BenefitsAsia%20V2/BA2%20Deployment/JIRA%20Scripts/Staging/SGHBBAIIALL-10253/04_10253_DBSSG_AddDependantSecondandMore.sql";
            string destinationUrl = @"C:\\04_10253_DBSSG_AddDependantSecondandMore.sql";

            //string sourceUrl = "http://usdfw13as15:41090/sites/HB/HB/Asia%20Documents/BenefitsAsia%20V2/BA2%20Deployment/JIRA%20Scripts/Staging/SGHBBAIIALL-10253";
            //string destinationUrl = @"C:\\SGHBBAIIALL-10253";

            usdfw13as15.FieldInformation fieldInfo = new usdfw13as15.FieldInformation();
           
            usdfw13as15.FieldInformation[] fieldInfoArray = { fieldInfo };
            usdfw13as15.CopyResult cResult1 = new usdfw13as15.CopyResult();
            usdfw13as15.CopyResult cResult2 = new usdfw13as15.CopyResult();
            usdfw13as15.CopyResult[] cResultArray = { cResult1, cResult2 };

            //Receive a Document Contents  into Byte array (filecontents)
            byte[] fileContents = new Byte[4096];
            copyService.GetItem(sourceUrl, out fieldInfoArray, out fileContents);

           

            //Create a new file and write contents to that document
            FileStream fStream = new FileStream(destinationUrl, FileMode.Create, FileAccess.ReadWrite);
            fStream.Write(fileContents, 0, fileContents.Length);
            fStream.Close();
Well Windows 7 and Outlook 2010 can sync a document library locally with your PC.  Have you consider that?

However, the easiest way is using a feature most people don't know about Sharepoint.
Change http://usdfw13as15:41090/sites/HB/HB/Asia%20Documents/BenefitsAsia%20V2/BA2%20Deployment/JIRA%20Scripts/Staging/SGHBBAIIALL-10253
into
\\usdfw13as15:41090\sites\HB\HB\Asia Documents\BenefitsAsia V2\BA2 Deployment\JIRA Scripts\Staging\SGHBBAIIALL-10253
 then just use standard file copy methods in C#
 
As long as you have the web client service running on your PC you can access any SharePoint path as a UNC path.
Hi All,

Below code works from me, to get all the files in a sharepoint folder, i am using List.asmx, copy.asmx.
protected void Button1_Click(object sender, EventArgs e)
        {
            string siteUrl = @"http://usdfw13as15:41090/sites/HB/HB";
            string documentLibraryName = @"Asia Documents";
           
            WSList.Lists wsList = new WSList.Lists();
            wsList.UseDefaultCredentials = true;
            wsList.PreAuthenticate = true;
            wsList.Credentials = System.Net.CredentialCache.DefaultCredentials;
            wsList.Url = siteUrl + @"/_vti_bin/lists.asmx";

            // get a list of all top level lists
            XmlNode allLists = wsList.GetListCollection();

            // load into an XML document so we can use XPath to query content
            XmlDocument allListsDoc = new XmlDocument();

            allListsDoc.LoadXml(allLists.OuterXml);

            // allListsDoc.Save(@"c:\allListsDoc.xml"); // for debug
            XmlNamespaceManager ns = new XmlNamespaceManager(allListsDoc.NameTable);

            ns.AddNamespace("d", allLists.NamespaceURI);

            // now get the GUID of the document library we are looking for
            XmlNode dlNode = allListsDoc.SelectSingleNode("/d:Lists/d:List[@Title='" + documentLibraryName + "']", ns);

            if (dlNode != null)
            {
                // obtain the GUID for the document library and the webID
                string documentLibraryGUID = dlNode.Attributes["ID"].Value;
                string webId = dlNode.Attributes["WebId"].Value;

                Console.WriteLine("Opening folder '{0}' GUID={1}", documentLibraryName, documentLibraryGUID);
               
                // create ViewFields CAML
                XmlDocument viewFieldsDoc = new XmlDocument();
                XmlNode ViewFields = AddXmlElement(viewFieldsDoc, "ViewFields", "");
                AddFieldRef(ViewFields, "GUID");
                AddFieldRef(ViewFields, "ContentType");
                AddFieldRef(ViewFields, "BaseName");
                AddFieldRef(ViewFields, "Modified");
                AddFieldRef(ViewFields, "EncodedAbsUrl");

                //viewFieldsDoc.Save(@"c:\viewFields.xml"); // for debug
                // create QueryOptions CAML
                XmlDocument queryOptionsDoc = new XmlDocument();
                XmlNode QueryOptions = AddXmlElement(queryOptionsDoc, "QueryOptions", "");
                AddXmlElement(QueryOptions, "Folder", @"Asia Documents\BenefitsAsia V2\BA2 Deployment\JIRA Scripts\Staging\SGHBBAIIALL-10884");
               
                AddXmlElement(QueryOptions, "IncludeMandatoryColumns", "FALSE");
                // this element is the key to getting the full recusive list

                XmlNode node = AddXmlElement(QueryOptions, "ViewAttributes", "");
                AddXmlAttribute(node, "Scope", "Recursive");
                //queryOptionsDoc.Save(@"c:\queryOptions.xml"); // for debug

                // obtain the list of items in the document library
                XmlNode listContent = wsList.GetListItems(documentLibraryGUID, null, null, ViewFields, null, QueryOptions, webId);
                XmlDocument xmlResultsDoc = new XmlDocument();

                xmlResultsDoc.LoadXml(listContent.OuterXml);
                ns = new XmlNamespaceManager(xmlResultsDoc.NameTable);

                ns.AddNamespace("z", "#RowsetSchema");
                // xmlResultsDoc.Save(@"c:\listContent.xml"); // for debug

                XmlNodeList rows = xmlResultsDoc.SelectNodes("//z:row", ns);

                if (rows.Count == 0)
                {
                    Console.WriteLine("No content found");

                }

                WSCopy.Copy copyService = new WSCopy.Copy();
                copyService.Url = siteUrl + "/_vti_bin/copy.asmx";
                copyService.Credentials = System.Net.CredentialCache.DefaultCredentials;

                foreach (XmlNode row in rows)
                {
                    //string str =row.Attributes["ows_ContentType"].Value + " " + row.Attributes["ows_GUID"].Value + " :: " + row.Attributes["ows_BaseName"].Value;
                    //string str = row.Attributes["ows_EncodedAbsUrl"].Value;

                    string sourceUrl = row.Attributes["ows_EncodedAbsUrl"].Value;
                    string destinationUrl = @"C:\\" + row.Attributes["ows_BaseName"].Value + ".sql";

                    WSCopy.FieldInformation fieldInfo = new WSCopy.FieldInformation();

                    WSCopy.FieldInformation[] fieldInfoArray = { fieldInfo };
                    WSCopy.CopyResult cResult1 = new WSCopy.CopyResult();
                    WSCopy.CopyResult cResult2 = new WSCopy.CopyResult();
                    WSCopy.CopyResult[] cResultArray = { cResult1, cResult2 };

                    //Receive a Document Contents  into Byte array (filecontents)
                    byte[] fileContents = new Byte[4096];
                    copyService.GetItem(sourceUrl, out fieldInfoArray, out fileContents);

                    //Create a new file and write contents to that document
                    FileStream fStream = new FileStream(destinationUrl, FileMode.Create, FileAccess.ReadWrite);
                    fStream.Write(fileContents, 0, fileContents.Length);
                    fStream.Close();

                }
            }
        }

        public static XmlNode AddXmlElement(XmlNode parent, string elementName, string elementValue)
        {
            XmlNode element = parent.AppendChild(parent.OwnerDocument.CreateNode(XmlNodeType.Element, elementName, ""));
            if (elementValue != "")
                element.InnerText = elementValue;
            return (element);
        }

        public static XmlNode AddXmlElement(XmlDocument parent, string elementName, string elementValue)
        {
            XmlNode element = parent.AppendChild(parent.CreateNode(XmlNodeType.Element, elementName, ""));
            if (elementValue != "")
                element.InnerText = elementValue;
                return (element);
        }

        public static XmlNode AddXmlAttribute(XmlNode element, string attrName, string attrValue)
        {
            XmlNode attr = element.Attributes.Append((XmlAttribute)element.OwnerDocument.CreateNode(XmlNodeType.Attribute, attrName, ""));
            if (attrValue != "")
                attr.Value = attrValue;
            return (attr);
        }


        public static void AddFieldRef(XmlNode viewFields, string fieldName)
        {
            XmlNode fieldRef = AddXmlElement(viewFields, "FieldRef", "");
            AddXmlAttribute(fieldRef, "Name", fieldName);
        }
 

Well it might work but it will be painfully slow.  The strategy I provided is faster with far less code.