[Fix]-System.Runtime.InteropServices.COMException The handle is invalid
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.
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);
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))
Use Server.MapPath to locate the exact path of file as follows:
System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(path));
The IIS users account does not have permission to write to or read from a file.
Environmental issue such as Impersonation turned on with application pool running as ApplicationPoolIdentity.
Use the below code as suggested:
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
// This End() method will raise error when the website is published
// Hence preferred way is to use Flush() method.
// finally use the end method