Is there a way to read a .msg file without using x32 libraries in C#?

154 Views Asked by At

I am working on a form which has a PictureBox with the DragAndDrop property enabled.

What I want to accomplish is to make the users able to drag an email from the Microsoft Outlook application.

I searched for many solutions but most of them suggest using the Microsoft.Office.Interop.Outlook.MailItem, but I readed that it is only available in x32.

The DragEnter event that I have looks like this:

private void DragDrop_DragEnter(object sender, DragEventArgs e)
{
   if (e.Data.GetDataPresent(DataFormats.UnicodeText))
   {
       e.Effect = DragDropEffects.Copy;
   }
   
   if (e.Data.GetDataPresent("FileGroupDescriptorW") &&
       e.Data.GetDataPresent("FileContents"))
   {
       e.Effect = DragDropEffects.Copy;
   }     
 }

Let me know if I should change anything.

I tried to read the message with a FileStream, but the stored file seems to be empty, this is the code:

// Get the .msg file contents as a stream
Stream msgFileStream = (Stream)e.Data.GetData("RenPrivateSourceFolder");

try
{
    // Create a FileStream for the target file
    using (FileStream targetFs = new FileStream(_defaultPath + ft.GetFileName(_ID.ToString(), _defaultPath, ".eml"), FileMode.Create, FileAccess.Write))
    {
        // Copy the .msg contents from the stream to the target file
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = msgFileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            targetFs.Write(buffer, 0, bytesRead);
        }

        Console.WriteLine("File copied successfully.");
    }
}
catch (Exception ex)
{
     Console.WriteLine(ex.HResult);
}
finally
{
     msgFileStream.Close();
}

And now that I have provided all the information that is by my hand, is there a way to be able to drag files from Microsoft Outlook to the form and store the .msg file without using this x32 library?

1

There are 1 best solutions below

2
Dmitry Streblechenko On BEST ANSWER

Microsoft.Office.Interop.Outlook.MailItem works perfectly fine whether your code is 32 or 64 bit no matter what the bitness of your app is - Outlook is an out-of-proc COM server and works across processes with any bitnesses.

You can of course read the contents of an MSG file without using OOM - there are a few C# libraries that will do that for you, e.g. https://github.com/Sicos1977/MSGReader