0 votes

How to use the "AddAttachment" method of FluentMail's type if the attachment file is already opened ?

by

1 Answer

0 votes

MailBuilder.AddAttachment(string path) as well as IFluentMail.AddAttachment(string path) both use System.IO.File.OpenRead(string path) under the hood to open a file and add it as an attachment to the newly created email.

This means that FileShare.Read is used.

FileShare.Read means: "open this file for me successfully, only if any prior openers have opened it for reading only".

Mail.dl won't be able to open the file unless the other aplication/process, which has the file open, doesn't allow for shared reads or has the file opened for 'write'.

You may want to try FileShare.ReadWrite. This way you'll be able to read the file other application has opened for writing.

However have in mind, that the other process might change the data you're reading, while you read it. Your code should be able to handle incompletely written data or such changes:

using (Stream s = System.IO.File.Open(fullFilePath, 
                                      FileMode.Open, 
                                      FileAccess.Read, 
                                      FileShare.ReadWrite))
{
}

Here's the sample that reads all data from the file:

byte[] data;
using (Stream stream = System.IO.File.Open("c:\\test.txt",
                          FileMode.Open,
                          FileAccess.Read,
                          FileShare.ReadWrite))
{
    int offset = 0;
    int count = (int)stream.Length;
    data = new byte[count];
    while (count > 0)
    {
        int read = stream.Read(data, offset, count);
        if (read == 0)
        {
            throw new EndOfStreamException();
        }
        offset += read;
        count -= read;
    }
}

You can use AddAttachment(byte[] data) to add it as email's attachment then:

...
.AddAttachment(new byte[] { 1, 2, 3 })
    .SetFileName("attachment1.dat")
...
by (298k points)
...