Programmatically downloaded file is larger than it should be
- by Dan Revell
I'm trying to download a file from SharePoint. The file itself is an InfoPath template although this is probably inconsequential.
If I put the url into internet explorer and save the file to disk, it comes in at 4.47KB and works correctly. If I try to download from the same Url in code the it comes back as 21.9KB and is corrupt. Why it's coming down as corrupt I'm trying to work out.
The following are two ways of downloading the file that both produce the corrupt file at 21.9KB:
/// web client
{
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
wc.DownloadFile(templateUri, file);
byte[] bytes = wc.DownloadData(templateUri);
}
/// web request
{
WebRequest request = WebRequest.Create(templateUri);
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse responce = request.GetResponse();
StreamReader sr = new StreamReader(responce.GetResponseStream());
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sr.ReadToEnd());
}
And this is how I write the data to disk
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(bytes, 0, bytes.Length);
}