SharePoint 2010: Downloading File using Server Object Model
Well I must confess that I could not find any code snippet that could let us download a document using server object model. Everytime I searched for such a thing, I always bumped into Client object model. So here is the code that lets us do that, although not using a server object model rather simple web request.
public static Boolean DownLoadFile(string strURL, string strDownloadFilePath, string UserID, string Password)
{
HttpWebRequest request;
HttpWebResponse response = null;
try
{
request = (HttpWebRequest)WebRequest.Create(strURL);
//request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Credentials = new System.Net.NetworkCredential(UserID, Password);
request.Timeout = 10000;
request.AllowWriteStreamBuffering = false;
response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
//Write to disk
if (File.Exists(strDownloadFilePath))
{
File.Delete(strDownloadFilePath);
}
FileStream fs = new FileStream(strDownloadFilePath, 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();
return true;
}
catch (Exception)
{
throw;
}
}
Comments
Post a Comment