Dailycode.info

Short solution for short problems

Open a file from the file system in a web browser. (+Demo project)

I included a demo solution, you can download it at the botom.

It sounds easy, just put the file as hyperlink on the system and let the user click the link…

Yes that’s easy, but what if the file needs to be opened from the code behind? I tried to use the Process.start at first, which did the trick. Only when I was working locally, after deploying on the server it stopped working, and it has something to do with the right of the application pool user to the local user’s desktop. So looking for a different solution, I came up with the following solution which works fine for IE, Chrome, Firefox and Safari.

The solution involves 2 pages. The first page has the links to the documents and when clicked, the document needs to be opened.


 

The second page is an empty aspx page where I generate the code for showing the document in the page load event.

After clicking on the link on the first page, I save the url of the document in the session and on the second page I get the url from the session.

On the first page, the click event of a button is triggered and then I get the url of the document from the selected line. I add the url to the Session so I can get it later on the second page. The code on the click event of the first page looks like this:


 

protected void btnView_Click(object sender, EventArgs e)

{

    string[] sfield = { _sKeyField };

    string docUrl = Convert.ToString(grdAttachments.GetRowValues(grdAttachments.FocusedRowIndex, sfield));

 

    try

    {

        Session.Add("OpenFileUrl", docUrl);

        Response.Redirect("OpenFile.aspx", false);

    }

    catch (ThreadAbortException)

    { }

    catch (Exception er)

    {

        lblError.Text = er.Message;

    }

}

 

 

So fairly easy code. Then when the second page (OpenFile.aspx) get loaded, the following code is triggered:

protected void Page_Load(object sender, EventArgs e)

{

    try

    {

        Loadfile();

    }

    catch (Exception er)

    {

        lblError.Text = er.Message;

    }

}

 

private void Loadfile()

{

    if (Session["OpenFileUrl"] != null)

    {

        // Get the physical Path of the file(test.doc)

        //string filepath = Server.MapPath();

 

        // Create New instance of FileInfo class to get the properties of the file being downloaded

        FileInfo file = new FileInfo(Session["OpenFileUrl"].ToString());

 

        // Checking if file exists

        if (file.Exists)

        {

            // Clear the content of the response

            Response.ClearContent();

 

            // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header

            //Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);

            Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);

 

            // Add the file size into the response header

            Response.AddHeader("Content-Length", file.Length.ToString());

 

            // Set the ContentType

            Response.ContentType = ReturnExtension(file.Extension.ToLower());

 

            // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)

            Response.TransmitFile(file.FullName);

 

            // End the response

            Response.End();

        }

    }

}

 

To complete all the code you need to show the document, here’s the ReturnExtension method:

private string ReturnExtension(string fileExtension)

{

    switch (fileExtension)

    {

        case ".htm":

        case ".html":

        case ".log":

            return "text/HTML";

        case ".txt":

            return "text/plain";

        case ".doc":

            return "application/ms-word";

        case ".tiff":

        case ".tif":

            return "image/tiff";

        case ".asf":

            return "video/x-ms-asf";

        case ".avi":

            return "video/avi";

        case ".zip":

            return "application/zip";

        case ".xls":

        case ".csv":

            return "application/vnd.ms-excel";

        case ".gif":

            return "image/gif";

        case ".jpg":

        case "jpeg":

            return "image/jpeg";

        case ".bmp":

            return "image/bmp";

        case ".wav":

            return "audio/wav";

        case ".mp3":

            return "audio/mpeg3";

        case ".mpg":

        case "mpeg":

            return "video/mpeg";

        case ".rtf":

            return "application/rtf";

        case ".asp":

            return "text/asp";

        case ".pdf":

            return "application/pdf";

        case ".fdf":

            return "application/vnd.fdf";

        case ".ppt":

            return "application/mspowerpoint";

        case ".dwg":

            return "image/vnd.dwg";

        case ".msg":

            return "application/msoutlook";

        case ".xml":

        case ".sdxl":

            return "application/xml";

        case ".xdp":

            return "application/vnd.adobe.xdp+xml";

        default:

            return "application/octet-stream";

    }

 

}

OpenDocDemo.zip (27.30 kb)