Posts Tagged ‘C#’

Drag Outlook Attachment To Your WinForm

July 20, 2010

My applications usually allow users to drag and drop Outlook attachments and save these as files. I have a simple method which saves the memory stream from Outlook to a temporary file and returns the path to the file.

Here is the function

Public Function GetOutlookAttachment(ByVal e As System.Windows.Forms.DragEventArgs) As String
Dim theStream As IO.Stream = DirectCast(e.Data.GetData("FileGroupDescriptor"), IO.Stream)
Dim fileGroupDescriptor As Byte() = New Byte(511) {}
theStream.Read(fileGroupDescriptor, 0, 512)

' used to build the filename from the FileGroupDescriptor block
Dim fileName As New System.Text.StringBuilder("")

' this trick gets the filename of the passed attached file
Dim i As Integer = 76
While fileGroupDescriptor(i) <> 0
i += 1
End While
Dim path As String = IO.Path.GetTempPath()

' put the zip file into the temp directory
Dim theFile As String = path + fileName.ToString()

Dim ms As IO.MemoryStream = DirectCast(e.Data.GetData("FileContents", True), IO.MemoryStream)

' allocate enough bytes to hold the raw data
Dim fileBytes As Byte() = New Byte(ms.Length - 1) {}

' set starting position at first byte and read in the raw data
ms.Position = 0
ms.Read(fileBytes, 0, CInt(ms.Length))

' create a file and save the raw zip file to it
Dim fs As New IO.FileStream(theFile, IO.FileMode.Create)
fs.Write(fileBytes, 0, CInt(fileBytes.Length))

' close the file

Return theFile
End Function

This function can be called like this

Private Sub MyForm_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop

If e.Data.GetFormats(False)(1) = "RenPrivateFileAttachments" Then

Dim FilePath as String = GetOutlookAttachment(e)

End If

End Sub