[Fix]-System.Runtime.InteropServices.COMException The handle is invalid

Wikitechy | 2595 Views | asp.net | 28 May 2016



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))

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.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
// This End() method will raise error when the website is published
// Hence preferred way is to use Flush() method.
// finally use the end method		


Bug Bounty
IOT Hackathon

Join our Community