Short solution for short problems

IIS copy files to file share in API or web site

Recently, I needed to copy some files from a database to a file share in a .Net web API that runs on an IIS. First I was trying to run the application pool using a domain user, but I couldn't get it working. The application pool keeps stopping, even if the username and password is correct and the local policies are correct.

So I found another better way to do it. In stead of giving the user permissions on the file share. I gave the server permissions on the file share. Then I ran the application pool under the NetworkService and it works.

On the file share under security, put DOMAIN\SERVERNAME and give modify rights (do not forget to include computers in de AD search). Thats it. Now the server can write to this specific location, no harm can be done. In fact, giving a user permissions can be more dangerous, because he can access it anywhere.

FileDialog default settings.


I was using several ‘Open’ and ‘Save’ file dialogs on my screen, all for importing or exporting xml files. Instead if setting the default parameters for each dialog over again, I made this easy function that helps to set the default parameters:

    Private Shared Sub DialogInit(ByRef dialog As FileDialog)

        dialog.InitialDirectory = Environment.SpecialFolder.Desktop

        dialog.DefaultExt = "xml"

        dialog.Filter = "XML|*.xml"

    End Sub


Then all file dialogs call this method to set the default parameters and all dialogs act the same:

Using dialog As New OpenFileDialog

'dialog.InitialDirectory = Environment.SpecialFolder.Desktop 

           'dialog.DefaultExt = "xml"

           'dialog.Filter = "XML|*.xml"


           If dialog.ShowDialog() <> DialogResult.OK Then Return

           xmlFile = dialog.FileName

End Using


Another example:

Using dialog As New SaveFileDialog()


           If dialog.ShowDialog() <> DialogResult.OK Then Return

           xmlFile = dialog.FileName

End Using


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




        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)






    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



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



            // End the response






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";


            return "application/octet-stream";




OpenDocDemo.zip (27.30 kb)