Adding an opened Office document as an attachment

0 votes
asked Jan 9, 2013 by Rebex KB (8,210 points)
edited Oct 24, 2013

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
answered Jan 9, 2013 by Jan Sotola (16,540 points)
edited Jan 9, 2013
 
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);
}
...