简体   繁体   中英

ASP.net download and save file in user folder

I am trying to save a file to the user pc but I am not able to do it. This method gives error since is trying to save the file in C somewhere. I understand it is not approriate. I would like to save the file in the download folder or prompt the user with a file dialog.

void SaveReport(Telerik.Reporting.Report report, string fileName)
{
    ReportProcessor reportProcessor = new ReportProcessor();
    Telerik.Reporting.InstanceReportSource instanceReportSource = new Telerik.Reporting.InstanceReportSource();
    instanceReportSource.ReportDocument = report;
    RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, null);

    using (FileStream fs = new FileStream(fileName, FileMode.Create))
    {
        fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
    }
}

How can I save the file in the download folder of the user machine or prompt a filedialog to allow the user to choose the destination?

You can't force the place the file is downloaded to.

In your code, you shouldn't write to file, but to the OutputStream from the response.

RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, null);

HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"file.pdf\"");
HttpContext.Current.Response.OutputStream.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);

Filestream will write to a file on server and not on the client's machine.

Try writing the document bytes to response output stream and a content-disposition http header to response.

Response.AddHeader("Content-Disposition", "attachment; filename=\\"" + fileName + "\\"");

This would prompt user for the file download based on browser setting.

You cannot control which directory file goes in in the client's machine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM