Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:emailsmessage01
                attachments
 c:emailsmessage02
                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:messagesmessage1";
        DirectoryInfo attachmentDirectory = new DirectoryInfo(attachmentDirectoryPath);
        FileInfo[] attachments = attachmentDirectory.GetFiles();
        foreach (FileInfo attachment in attachments)
        {
            mail.Attachments.Add(new Attachment(attachment.FullName));
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
498 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...