[Fix]-System.Runtime.InteropServices.COMException The handle is invalid
Scenario:
The above exception occurs with a file download. Asp.NET 2.0 is installed in the machine with IIS7. Hence the application creates files in a shared folder and those files are displayed in the web page via hyperlinks.
When the file size is 0Kb, the web browser displays a successful download message, but when the file size is more than 0Kb, then the asp.net application throws the above exception.
Error:
The event viewer shows the log as “TransmitFile failed”. File Name: \\\\wikitechy-server\\outputFile\\24.txt, HRESULT: 0x800700a1.
The code that make the transfer is:
Response.AddHeader("Content-disposition", "attachment; filename=" + filename);
Response.ContentType = "text/plain";
Response.TransmitFile(path + filename);
Response.Flush();
Response.End();
NOTE: Framework 3.5 SP1 is used with Windows Communication Foundation.
System.Runtime.InteropServices.COMException: The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))
Fix 1:
Use Server.MapPath to locate the exact path of file as follows:
System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(path));
Fix 2:
The IIS users account does not have permission to write to or read from a file.
Fix 3:
Environmental issue such as Impersonation turned on with application pool running as ApplicationPoolIdentity.
Fix 4:
Use the below code as suggested:
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.TransmitFile(file.FullName);
// This End() method will raise error when the website is published
// Hence preferred way is to use Flush() method.
//Response.End();
Response.Flush();
// finally use the end method
Response.End();