将文件作为附件发送后锁定文件

Joh*_*ann 13 c# attachment locked-files

我发送文件作为附件:

            // 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);
Run Code Online (Sandbox Code Playgroud)

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

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

                    }
                    catch (Exception ex)
                    {
                    }
Run Code Online (Sandbox Code Playgroud)

它抛出了一个异常,即该文件已在另一个进程中使用.如何解锁此文件以便将其移动到此位置?

ale*_*exn 24

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

message.Dispose();
File.Move(...)
Run Code Online (Sandbox Code Playgroud)

处置MailMessage时,将释放所有锁定和资源.


Mat*_*zer 11

您需要利用"使用"关键字:

using(Attachment att = new Attachment(...))
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

那是因为"使用"确保在代码块执行结束时调用IDisposable.Dispose方法.

每当你使用一些管理某些资源的类时,检查它是否是IDisposable,然后使用"using"块,你不需要关心手动处理调用IDisposable.Dispose.


Gre*_*g B 6

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

  • message.Dispose() 成功了 :) 感谢您的帮助 Greg (2认同)

Nei*_*ght 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
}
Run Code Online (Sandbox Code Playgroud)