Thursday, July 23, 2009

Download files in c#

This code shows how to download files of any type from applciation

private void DownloadFile( string fname)
{
try
{
string path = MapPath( fname );
string name = System.IO.Path.GetFileName( path );
string ext = System.IO.Path.GetExtension( path );
string type = "";
// set known types based on file extension
if ( ext != null )
{
switch( ext.ToLower() )
{
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".doc":
case ".rtf":
type = "Application/msword";
break;
case ".xml":
type = "Application/xml";
break;
case ".zip":
type = "application/zip";
break;
}
}
Response.AppendHeader( "content-disposition","attachment; filename=" + name );
if ( type != "" )
Response.ContentType = type;
Response.WriteFile( path );
}
catch(Exception ex)
{
new PowerXEditor.BL.CommonUtility().RegisterError(ex);
}
Response.End();
}

No comments:

Post a Comment