I have written the following code to download a file from sharepoint. The downloded file works fine in only some machines. For others, it says that the file is corrupted. The issue is for MS Office and image files, however the PDF is not having any issues. We have identified the issue of corruption as due to the addition of a hexadecimal number at the top of the file contents. When it is removed, the file gets opened correctly. The hexadecimal character has been traced out to be representing the file size in bytes. Why this is happening only in some machines and how can we fix it?
private void DownloadFile()
{
SPListItem item = GetFileFromSharepoint();
if (item != null)
{
byte[] bytes = item.File.OpenBinary();
Response.ClearContent();
Response.ClearHeaders();
string fileType = string.Empty;
fileType = item["FileFormat"].ToString();
Response.AppendHeader("Content-Disposition",
string.Format("attachment; filename= {0}", item["Filename"].ToString().Replace(" ", "")));
Response.ContentType = GetContentType(fileType);
//Check that the client is connected and has not closed the connection after the request
if (Response.IsClientConnected)
{
Response.BinaryWrite(bytes);
}
}
Response.Flush();
Response.Close();
}