删除文件时,另一个进程正在使用文件

时间:2014-05-05 14:14:19

标签: c#

我有创建pdf的功能,然后通过附件中的邮件发送。

创建pdf的功能:

public string CreatePdf()
        {

            try
            {
                using (document = new Document())
                {

                    if (File.Exists(filePath))
                    {
                        workStream.Dispose();
                        File.Delete(filePath);
                    }
                // LOGIC to Create PDF
                    return filePath;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                document.Close();
                document.Dispose();
                workStream.Close();
            }
        }

要添加到附件:

myMail.attachment = new Attachment(new CreatePdf());

当我第一次创建文件时,它被创建正常,但是当我再次尝试创建pdf时,我在File.Delete(filePath)

上收到以下错误
The process cannot access the file because it is being used by another process.

我看到了其他类似的问题,但无法确定需要关闭的内容,因为我关闭了所有内容。

2 个答案:

答案 0 :(得分:1)

我发现您提供的代码没有任何问题。我个人认为你没有关闭或处理类似附件的东西。为什么不尝试使用using语句实现附件?

答案 1 :(得分:0)

感谢SteveLynx解决了它并不知道这是否正确。 Attachments类是IDisposable所以我认为它将自己处理流。我刚刚添加了attachments.dispose()