Many times we come across to a situation where in we need to download the document, PowerPoint files, excel files or just any other file from SharePoint.
However we are not on the server or let’s say we need to show those documents in some ASP.Net application and show their content on some ASP.Net page.
At that time we need to use the web service provided by SharePoint and then we are able to download any document from any document library in the site.
Following is the simple code that you need to write to pull the document to your local machine.
First add the web reference and then add URL of your SharePoint server + “_vti_bin/copy.asmx"”.
Then give it a proper name, so that you can reference in the code.
Then write down simple code shown below. In this example I am downloading simple ppts file from SharePoint server and copying it in C drive. I am passing default credential as I am in the same domain connected with windows authentication. However if you are not connected, then pass the user name and password of administrator who has a permission over the site.
Here DownloadSharePointDocument is the name of my web reference proxy class.
DownloadSharePointDocument.Copy copyService = new EncryptAndDecrypt.DownloadSharePointDocument.Copy();
copyService.Url = "https://intranet.eclipsnet.com/" + "_vti_bin/copy.asmx";
copyService.Credentials = System.Net.CredentialCache.DefaultCredentials;
string sourceUrl = “{server url} + {document lib name} + {file name}”;
string destinationUrl = @"C:\\Downloaded.ppsx"; // location where file to be downloaded
DownloadSharePointDocument.FieldInformation fieldInfo = new DownloadSharePointDocument.FieldInformation();
DownloadSharePointDocument.FieldInformation[] fieldInfoArray = { fieldInfo };
DownloadSharePointDocument.CopyResult cResult1 = new DownloadSharePointDocument.CopyResult();
DownloadSharePointDocument.CopyResult cResult2 = new DownloadSharePointDocument.CopyResult();
DownloadSharePointDocument.CopyResult[] cResultArray = { cResult1, cResult2 };
byte[] fileContents = new Byte[4096];
copyService.GetItem(sourceUrl, out fieldInfoArray, out fileContents);
FileStream fStream = new FileStream(destinationUrl, FileMode.Create, FileAccess.ReadWrite);
fStream.Write(fileContents, 0, fileContents.Length);
fStream.Close();
That is it. now you have the document in your machine.
4 comments:
Thank you for sharing very useful information.
How would you have the option to show open or save as dialog box?
Is it possible with copy webservice?
Unknown,
its depend upon your file type and browser support.
like if its .txt file then it can be open in browser directly but if you have some other type like .xyz which is not detectable by browser then it will ask for open/save as dialog.
Cheers, dude! Just the information I needed, as a noob sharepoint dev.
Post a Comment