由于IOException,无法删除该文件。它被另一个进程使用

时间:2012-08-23 20:03:23

标签: c# using ioexception

尝试删除文件时,我一直收到上述错误。请参阅代码注释以确切了解错误发生的位置。

foreach (string file in supportedFiles)
{
    if (file.EndsWith(".pdf"))
    {
        PDFImageExtractor.ExtractImagesFromPDF(
            file, 
            AppVars.TempFolder, 
            Path.GetFileNameWithoutExtension(file));
    }
}

foreach (string file in supportedFiles)
{
    if (file.EndsWith(".pdf"))
    {
        // I get the error here. 
        File.Delete(file);
    }
}

这是错误之前的代码,在PDFImageExtractor.ExtractImagesFromPDF方法中:

public static void ExtractImagesFromPDF(
    string sourcePdf, 
    string outputPath, 
    string fileName)
{
    // NOTE: This will only get the first image it finds per page.
    PdfReader pdf = new PdfReader(sourcePdf);
    RandomAccessFileOrArray raf = 
        new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);

    try
    {
        for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
        {
            PdfDictionary pg = pdf.GetPageN(pageNumber);
            PdfDictionary res = (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
            PdfDictionary xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));

            if (xobj != null)
            {
                foreach (PdfName name in xobj.Keys)
                {
                    PdfObject obj = xobj.Get(name);
                    if (obj.IsIndirect())
                    {
                        PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
                        PdfName type = 
                            (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));

                        if (PdfName.IMAGE.Equals(type))
                        {
                            int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(CultureInfo.InvariantCulture));
                            PdfObject pdfObj = pdf.GetPdfObject(XrefIndex);
                            PdfStream pdfStrem = (PdfStream)pdfObj;
                            byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                            if ((bytes != null))
                            {
                                using (MemoryStream memStream = new MemoryStream(bytes))
                                {
                                    memStream.Position = 0;
                                    System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
                                    // must save the file while stream is open.
                                    if (!Directory.Exists(outputPath))
                                        Directory.CreateDirectory(outputPath);

                                    string path = Path.Combine(outputPath, String.Format(@"{0}.jpg", fileName));

                                    using (EncoderParameters parms = new EncoderParameters(1))
                                    {
                                        parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
                                        // GetImageEncoder is found below this method
                                        ImageCodecInfo jpegEncoder = GetImageEncoder("JPEG");
                                        img.Save(path, jpegEncoder, parms);
                                    }

                                    //EncoderParameters parms = new EncoderParameters(1);

                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        pdf.Close();
    }
}

public static ImageCodecInfo GetImageEncoder(string imageType)
{
    imageType = imageType.ToUpperInvariant();

    foreach (ImageCodecInfo info in ImageCodecInfo.GetImageEncoders())
    {
        if (info.FormatDescription == imageType)
        {
            return info;
        }
    }
    return null;
}

我错过了在某处使用的地方!?

2 个答案:

答案 0 :(得分:3)

“raf”变量未使用且未关闭。它正在锁定文件。

RandomAccessFileOrArray raf = 
        new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);

答案 1 :(得分:2)

我想你的:

System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);

缺少使用。

PdfReader或RandomAccessFileOrArray是否实现了IDisposable?

可能很傻,但是值得使用Process Explorer查看是否还有其他文件句柄。