views:

39

answers:

2

I'm creating an Excel file in C# on my asp.net web site. Then, I want to save this file somewhere within the web server's files, and send that file to the browser for the user to download.

I've got it working on my local system in the dev environment, but I'm not getting the file addressing right.

  1. How can I store a file in "~\ParentFolder\SubFolder\file.ext".
  2. Then send that file to the browser for user download.

Any guidance would be much appreciated.

        String outputFile = Utilities.writeToExcelFile("", MapPath(@"~\ReportFiles\TempFiles\DropShipData.xls"), table);

    DownloadFile(outputFile);


       public void DownloadFile(string fname)
{
    string path = fname;
    string name = Path.GetFileName(path);
    string ext = Path.GetExtension(path);
    string type = "";
    // set known types based on file extension  
    if (ext != null)
    {
        switch (ext.ToLower())
        {
            case ".htm":
            case ".html":
            case ".aspx":
            case ".asp":
                type = "text/HTML";
                break;

            case ".xls":
            case ".xlsx":
            case ".csv":
                type = "Application/x-msexcel";
                break;

            case ".pdf":
                type = "Application/pdf";
                break;

            case ".txt":
                type = "text/plain";
                break;

            case ".doc":
            case ".docx":
            case ".rtf":
                type = "Application/msword";
                break;
        }
    }

    Response.AppendHeader("content-disposition",
        "attachment; filename=" + name);

    if (type != "")
        Response.ContentType = type;
    Response.WriteFile(path);
    Response.End();
}

Again, this works fine on my local pc, but when I move it to the server I get an error for accessing the path. And the path listed in the error code is NOT where I want the file to go.

+2  A: 

First store the file:

string physicalPath = Server.MapPath("~/ParentFolder/SubFolder/file.ext");
// returns c:\path\to\website\ParentFolder\SubFolder\file.ext

Then you could for example, tell the browser to redirect to that file

Response.Redirect("~/ParentFolder/SubFolder/file.ext");
M4N
hmmmm Response.Redirect, didn't think of that one.
Marc
A: 

You might also want to check and make sure that the account running the ASP.Net worker process, or the appropriate user if you're using Impersonation, has write privileges to the ReportFiles\TempFiles location. A lot of times the error occurs because the default privileges only give read access to the folders in your website.

Dillie-O
where do I need to grant this permission?
Marc
On the folder itself. Typically you woudl grant it to "Network Service" or whatever the ASP.Net process is running under.
Dillie-O
Looks like this did the trick! Thanks man!
Marc