0 votes
by (8.6k points)
edited

I create attachments like this:

var msg = new MailMessage();
Attachment attachment = new Attachment(path, displayName);
msg.Attachments.Add(attachment);

In general it is working fine.

But if I send a file that is currently opened in Microsoft Word or Excel, I get this exception:

System.IO.IOException: The process cannot access the file 'C:test.docx' because it is being used by another process.

However, adding an opened file to another mail client (like Microsoft Outlook) works well.

Applies to: Rebex Secure Mail

1 Answer

0 votes
by (18.1k points)
edited
 
Best answer

When adding an attachment, Rebex.Mail actually opens the file with a FileShare.Read sharing mode. It is a default mode for opening files.

If you prefer to override this mode, you can open the attachment in your program and pass it to the Rebex attachment object as a stream.

Here is an example:

var msg = new MailMessage();
using (var stream = new FileStream(@"C:\test.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
     Attachment attachment = new Attachment(stream, "test.docx");
     msg.Attachments.Add(attachment);
}
...