16

我将文件作为附件发送:

            // Create  the file attachment for this e-mail message.
            Attachment data = new Attachment(filePath, MediaTypeNames.Application.Octet);
            // Add time stamp information for the file.
            ContentDisposition disposition = data.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(filePath);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(filePath);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(filePath);
            // Add the file attachment to this e-mail message.
            message.Attachments.Add(data);

然后我想将文件移动到另一个文件夹,但是当我尝试这样做时

                    try
                    {
                        //File.Open(oldFullPath, FileMode.Open, FileAccess.ReadWrite,FileShare.ReadWrite);
                        File.Move(oldFullPath, newFullPath);

                    }
                    catch (Exception ex)
                    {
                    }

它抛出一个异常,该文件已在另一个进程中使用。我怎样才能解锁这个文件,以便它可以移动到这个位置?

4

6 回答 6

26

处置你的message遗嘱会为你解决这个问题。在移动文件之前尝试调用Dispose您的消息,如下所示:

message.Dispose();
File.Move(...)

处理 MailMessage 时,会释放所有锁和资源。

于 2011-03-04T08:47:12.823 回答
13

您需要利用“使用”关键字:

using(Attachment att = new Attachment(...))
{
   ...
}

这是因为“使用”确保 IDisposable.Dispose 方法在代码块执行结束时被调用。

每当您使用某个管理某些资源的类时,请检查它是否为 IDisposable,然后使用“使用”块,您无需关心手动处理调用 IDisposable.Dispose。

于 2011-03-04T08:47:29.487 回答
6

附件IDisposable并且应该在发送后正确处理以释放文件上的锁定

于 2011-03-04T08:44:16.943 回答
5

为了防止发生此文件锁定,您可以使用using,因为这将自动处理对象:

using (Attachment data = new Attachment(filePath, MediaTypeNames.Application.Octet))
{
    // Add time stamp information for the file.             
    ContentDisposition disposition = data.ContentDisposition;   
    disposition.CreationDate = System.IO.File.GetCreationTime(filePath);
    disposition.ModificationDate = System.IO.File.GetLastWriteTime(filePath);
    disposition.ReadDate = System.IO.File.GetLastAccessTime(filePath);
    // Add the file attachment to this e-mail message.
    message.Attachments.Add(data); 
    // Add your send code in here too
}
于 2011-03-04T08:47:01.617 回答
3

这是处理附件的另一种方法,一旦你完成它们......

//  Prepare the MailMessage "mail" to get sent out...
await Task.Run(() => smtp.Send(mail));

//  Then dispose of the Attachments.
foreach (Attachment attach in mail.Attachments)
{
    //  Very important, otherwise the files remain "locked", so can't be deleted
    attach.Dispose();
}
于 2018-05-17T08:56:57.540 回答
0

一个共享的类似问题。我必须在给定的图像上使用 image.dispose() 才能对创建图像的文件做一些事情。

于 2016-06-19T16:02:13.850 回答