Tutorial :How do I programatically download a file from a sharepoint site?



Question:

I have a sharepoint site that has an excel spreadsheet that I need to download on a schedulad basis

Is this possible?


Solution:1

Why not just use wget.exe <url>. You can put that line in a batch file and run that through windows scheduler.


Solution:2

Yes it is possible to download the file from sharepoint. Once you have the url for the document, it can be downloaded using HttpWebRequest and HttpWebResponse.

attaching a sample code

    DownLoadDocument(string strURL, string strFileName)      {          HttpWebRequest request;          HttpWebResponse response = null;                request = (HttpWebRequest)WebRequest.Create(strURL);              request.Credentials = System.Net.CredentialCache.DefaultCredentials;              request.Timeout = 10000;              request.AllowWriteStreamBuffering = false;              response = (HttpWebResponse)request.GetResponse();              Stream s = response.GetResponseStream();                // Write to disk              if (!Directory.Exists(myDownLoads))              {                  Directory.CreateDirectory(myDownLoads);              }              string aFilePath = myDownLoads + "\\" + strFileName;              FileStream fs = new FileStream(aFilePath, FileMode.Create);              byte[] read = new byte[256];              int count = s.Read(read, 0, read.Length);              while (count > 0)              {                  fs.Write(read, 0, count);                  count = s.Read(read, 0, read.Length);              }                // Close everything              fs.Close();              s.Close();              response.Close();        }  

You can also use the GetItem API of Copy service to download a file.

        string aFileUrl = mySiteUrl + strFileName;          Copy aCopyService = new Copy();          aCopyService.UseDefaultCredentials = true;          byte[] aFileContents = null;          FieldInformation[] aFieldInfo;          aCopyService.GetItem(aFileUrl, out aFieldInfo, out aFileContents);  

The file can be retrieved as a byte array.


Solution:3

You can also do this:

try          {                 using (WebClient client = new WebClient())              {                  client.Credentials = new NetworkCredential("username", "password", "DOMAIN");                  client.DownloadFile(http_path, path);                                  }          }          catch (Exception ex)          {              MessageBox.Show("Error: " + ex.Message);          }  


Solution:4

The link the to document in Sharepoint should be a static URL. Use that URL in whatever solution you have to grab the file on your schedule.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »