问题描述
我有一个函数多数民众赞成在发送消息(他们中的很多)及其附件。
基本上,它遍历目录结构,例如从
C:\emails\message01
\attachments
C:\emails\message02
\attachments
消息的创建需要使用.NET C#标准的东西的地方。
创建所有的消息后......我有一个运行以后直接另一个功能是复制文件夹的消息到另一个位置。
但问题是 - 文件被锁定...
请注意:我不动的文件,只将它们复制....
这是如何复制锁定的文件,使用C#?
更新
>私人无效AddAttachments(邮件MAILMESSAGE)
{
串attachmentDirectoryPath =C:\messages\message1
DirectoryInfo的attachmentDirectory =新DirectoryInfo的(attachmentDirectoryPath);
的FileInfo [] =附件attachmentDirectory.GetFiles();
的foreach(附件中的FileInfo附件)
{
mail.Attachments.Add(新附件(attachment.FullName));
}
}
如何你是在读文件,以创建电子邮件?他们应该打开为只读,以文件共享
设置为 FileShare.ReadWrite
...然后他们不该 T为锁定。如果您使用的是的FileStream
你也应该让资源妥善处理包裹你的逻辑在使用
关键字。
更新:
我相信处理的邮件本身内部关闭资源和解锁文件:
使用(VAR邮件= MAILMESSAGE新())
{
AddAttachments(邮件);
}
//文件复制的代码应该在这里工作
I have a function thats sending messages ( a lot of them) and their attachments.
It basically loops through a directory structure and creates emails from a file structure for example
c:\emails\message01
\attachments
c:\emails\message02
\attachments
The creation of the messages takes place using .net c#, standard stuff.
After all messages are created... I have another function that runs directly afterwards that copies the message folder to another location.
Problem is - files are locked...
Note: I'm not moving the files, just copying them....
Any suggestions on how to copy locked files, using c#?
Update
I have this add attachments method
private void AddAttachments(MailMessage mail)
{
string attachmentDirectoryPath = "c:\messages\message1";
DirectoryInfo attachmentDirectory = new DirectoryInfo(attachmentDirectoryPath);
FileInfo[] attachments = attachmentDirectory.GetFiles();
foreach (FileInfo attachment in attachments)
{
mail.Attachments.Add(new Attachment(attachment.FullName));
}
}
How are you reading the files to create the email message? They should be opened as read-only, with a FileShare
set to FileShare.ReadWrite
... then they shouldn't be locked. If you are using a FileStream
you should also wrap your logic in the using
keyword so that the resource is disposed properly.
Update:
I believe disposing the mail message itself will close resources within it and unlock the files:
using (var mail = new MailMessage())
{
AddAttachments(mail);
}
// File copy code should work here
这篇关于SMTP发送被锁定了我的文件 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!