C# 如何解决将Excel文件保存到用户桌面时的问题?

C# 如何解决将Excel文件保存到用户桌面时的问题?,c#,asp.net,file-permissions,C#,Asp.net,File Permissions,尝试从c asp.net web应用程序将excel文件保存到用户桌面。测试时,这在本地计算机上运行良好,但在远程服务器上运行不好。有人能帮我解决这个问题吗?谢谢 代码: 错误: 看起来您可能正在使用Epplus excelPackage.SaveAsfi;。因此,如果使用asp.net作为标记,则可以将Excel文件发送到浏览器,用户将获得“保存文件”对话框 //convert the excel package to a byte array byte[] bin = excelPackag

尝试从c asp.net web应用程序将excel文件保存到用户桌面。测试时,这在本地计算机上运行良好,但在远程服务器上运行不好。有人能帮我解决这个问题吗?谢谢

代码:

错误:

看起来您可能正在使用Epplus excelPackage.SaveAsfi;。因此,如果使用asp.net作为标记,则可以将Excel文件发送到浏览器,用户将获得“保存文件”对话框

//convert the excel package to a byte array
byte[] bin = excelPackage.GetAsByteArray();

//clear the buffer stream
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;

//set the correct contenttype
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

//set the correct length of the data being send
Response.AddHeader("content-length", bin.Length.ToString());

//set the filename for the excel package
Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\"");

//send the byte array to the browser
Response.OutputStream.Write(bin, 0, bin.Length);

//cleanup
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();

此代码在服务器上执行。您正试图在服务器的“桌面”上保存一个文件。同意Steve的说法,但您的错误路径也是直接保存到C:\而不是桌面。我想你们更让我困惑了。因此,我应该将文件保存到服务器上的文件夹中吗?例如:c:\somefolder\然后将文件提供给用户保存到哪里?您只能向用户提供一个下载按钮,让他/她决定他/她要保存文件的位置。您必须牢记代码的执行位置和功能。此代码正在服务器上运行。你是否曾经访问过一个网站,并让它把随机文件放在你的计算机上它想要的任何地方?不难道你不认为如果网站能够做到这一点,这将是一个巨大的安全漏洞吗?如何从网站上获取计算机上的文件?网站提供文件供下载,然后用户选择将文件放在何处。因此,您需要了解如何在ASP.NET应用程序中提供下载文件。
//convert the excel package to a byte array
byte[] bin = excelPackage.GetAsByteArray();

//clear the buffer stream
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;

//set the correct contenttype
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

//set the correct length of the data being send
Response.AddHeader("content-length", bin.Length.ToString());

//set the filename for the excel package
Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\"");

//send the byte array to the browser
Response.OutputStream.Write(bin, 0, bin.Length);

//cleanup
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();