내 Asp.Net 응용 프로그램 중 하나에 문제가 있습니다. 내가 사용하는 DataTable에서 Excel 파일을 만들고 있습니다. 관련된 기능은 다음과 같습니다.Asp.Net 파일 스트림 IO 예외 : 프로세스가 다른 프로세스에서 사용 중이므로 파일에 액세스 할 수 없습니다.
public static void ExportToExcel(System.Data.DataTable Tbl, string ExcelFilePath)
{
try
{
if (Tbl == null || Tbl.Columns.Count == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Microsoft.Office.Interop.Excel._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (int i = 0; i < Tbl.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName;
}
// rows
for (int i = 0; i < Tbl.Rows.Count; i++)
{
// to do: format datetime values before printing
for (int j = 0; j < Tbl.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];
}
}
// check fielpath
if (ExcelFilePath != null && ExcelFilePath != "")
{
try
{
workSheet.SaveAs(ExcelFilePath);
excelApp.Quit();
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
+ ex.Message);
}
}
else // no filepath is given
{
excelApp.Visible = true;
}
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: \n" + ex.Message);
}
}
이 'new created'Excel 파일을 사용자의 컴퓨터로 보내야합니다. 사용자가이 파일을 다운로드합니다. 그리고 여기에 '다운로드 기능'입니다 :
public void FileDownload(string fileName)
{
Session["dosya"] = fileName;
string dosyaUrl = @Server.MapPath("/") + Session["dosya"].ToString() + ".xlsx"; //buradan sonra dosyamızı indirme işlemine başlıyoruz.
string yeni_dosya = Session["dosya"].ToString() + ".xlsx"; //biz işlem yapılacak dosyanın adını sessina attık oyle kullandık siz istediğiniz yolla yapabilirsiniz.
FileStream fs;
if (File.Exists(dosyaUrl))
{
fs = new FileStream(dosyaUrl, FileMode.Open, FileAccess.Read, FileShare.Read);
}
else
{
return;
}
byte[] buffer = new byte[(int)fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
fs.Flush();
fs.Close();
fs.Dispose();
Response.Clear();
Response.AddHeader("Content-Length", buffer.Length.ToString());//içeriğin uzunluğu AddHeader fonksiyonuna gonderiliyor...
Response.AddHeader("Content-Disposition", "attachment; filename=" + yeni_dosya);
Response.BinaryWrite(buffer);
File.Delete(dosyaUrl);
Response.End();
}
그리고이 두 가지 기능은 내 웹 페이지에서 버튼으로 제어된다.
코드 라인은 내가 예외를 얻고있다
fs.Read(buffer, 0, (int)fs.Length);
라인에 올 때 :
IO 예외는 사용자 코드에 의해 처리되지 않은했다 : 프로세스가 다른 사용 중이기 때문에 파일을 액세스 할 수 없습니다 프로세스
문제의 원인을 알 수 없습니다. 왜냐하면 나는 파일을 저장하고 닫고 있기 때문이다. 그리고 작업 관리자에서 Excel 파일에 대한 작업을 볼 수 없습니다. 그리고 예외는 함수 줄에 중단 점이있을 때 처리가 아니며 코드를 한 줄씩 진행합니다.
그래서 문제가 될 수 있습니까?