C# 传输文件和写入文件
我使用TransmitFile和WriteFile来编写Excel文件,但任何人都不能正常工作 我的代码是:C# 传输文件和写入文件,c#,asp.net,asp.net-mvc,excel,file,C#,Asp.net,Asp.net Mvc,Excel,File,我使用TransmitFile和WriteFile来编写Excel文件,但任何人都不能正常工作 我的代码是: // Get the Physical Path of the file(test.doc) string filepath = newFilePath; // Create New instance of FileInfo class to get the properties of the file being downloaded
// Get the Physical Path of the file(test.doc)
string filepath = newFilePath;
// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(filepath);
// Checking if file exists
if (file.Exists)
{
// Clear the content of the response
HttpContext.Current.Response.ClearContent();
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name));
// Add the file size into the response header
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
HttpContext.Current.Response.TransmitFile(file.FullName);
}
FileStream sourceFile = new FileStream(file.FullName, FileMode.Open);
float FileSize;
FileSize = sourceFile.Length;
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Length", getContent.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
HttpContext.Current.Response.BinaryWrite(getContent);
我将把它简化为:
public ActionResult ExcelDoc(string newFilePath)
{
string filepath = newFilePath;
// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(filepath);
// Checking if file exists
if (file.Exists)
{
var fileBytes = System.IO.File.ReadAllBytes(filepath);
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name));
return File(new MemoryStream(fileBytes), "application/vnd.ms-excel");
}
else
{
return Content("File does not exist");
}
}
导致任何错误。发生了什么错误?我没有看到任何Excel文件可供下载尝试放置一个try and catch并查看是否有任何异常。如果它依赖于浏览器,则没有任何异常?在response.writefile之后,我想看看save对话框,为什么你会使用
float
作为文件大小?我想在类中使用此代码,我必须返回什么类型?file?我会让类返回一个字节数组。这真是一个设计决策。