0

我正在使用 EPPlus 打开一个电子表格,然后用图片和信息填充它。当我尝试删除包含我用来填充电子表格的所有图片的文件夹时,我收到此文件正在与另一个应用程序一起使用的错误。释放使用的对象并关闭电子表格的正确方法是什么?

using (var package = new ExcelPackage(existingFile))
     {
        ExcelWorkbook workBook = package.Workbook;
        if (workBook != null)
        {
          if (workBook.Worksheets.Count > 0)
            {
              int i = 0;
              foreach(ExcelWorksheet worksheet in workBook.Worksheets)
              {
                xlWorkSeet1[i] = worksheet;
                i = i + 1;
              }

            }
        }

           //More code ...

           FileStream aFile = new FileStream(tempFolderPathAlt + saveas + ".xls",    FileMode.Create);
           byte[] byData = package.GetAsByteArray();
           aFile.Seek(0, SeekOrigin.Begin);
           aFile.Write(byData, 0, byData.Length);
           aFile.Close();

            xlWorkSeet1 = null;
            workBook = null;


      }//End using

     String P = Path.Combine(tempFolderPathAlt, "ExtractedFiles");
     bool directoryExists = Directory.Exists(P);
     if (directoryExists)
     Directory.Delete(P, true); // deletes sub-directories

我得到的错误是它试图删除我添加到电子表格中的照片。

在此处输入图像描述

4

1 回答 1

0

Try out following and please let me know whether this helps

int writeTimeout = 200;
using (var aFile = new FileStream(tempFolderPathAlt + saveas + ".xls",    FileMode.Create))
{
      aFile.WriteTimeout = writeTimeout;
      byte[] byData = package.GetAsByteArray();            
      aFile.Seek(0, SeekOrigin.Begin);            
      aFile.Write(byData, 0, byData.Length);            
      xlWorkSeet1 = null;             
      workBook = null;  
      Thread.Sleep(writeTimeout);
}
于 2012-10-16T09:14:06.007 回答