本文介绍了下载后文件已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我正在使用此代码下载整个应用程序正常工作的文件。
我正在尝试使用此代码下载Excel文件。下载后,当我尝试打开excel文件时,会弹出'警告文件已损坏,一些数据将被删除或丢失。检查后我发现在excel上应用的格式丢失了。我已经尝试了所有方法来做到这一点。请帮帮我
Hello everyone,
I am using this code to download file which is working fine in whole application.
I am trying to download Excel file using this code . After download when i try to open excel file, it pop up''s a warning that file is corrupted and some data will be removed or lost. After checking i found that the formatting applied on excel is lost.I have tried all ways to do this. Please help me out
System.IO.Stream iStream = null;
// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
// Identify the file to download including its path.
string filepath = strFileName;
// Identify the file name.
string filename = System.IO.Path.GetFileName(filepath);
try
{
// Open the file.
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
//if(strFileName.ToLower().Contains(".xls"))
//{
// Response.ContentType = "application/vnd.ms-excel";
//}
//else
//{
// Response.ContentType = "application/octet-stream";
//}
Response.AddHeader("Content-Disposition", "inline; filename=" + filename);
//Response.AddHeader("Content-Length", objFile.Length.ToString());
Response.ContentType = "application/vnd.ms-excel";
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the HTML output.
Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
Response.End();
}
catch (Exception ex)
{
// Trap the error, if any.
Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Response.Close();
}
推荐答案
// Length of the file:
int length;
.
.
.
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
to
to
// Length of the file:
int length = 0;
.
.
.
// Read the data in buffer.
length = iStream.Read(buffer, length, 10000);
不保证可以正常工作,如我只运行了我的代码。
Not guaranteed to work, as I have only run the code in my head.
这篇关于下载后文件已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!