OpenStreamOnFile vs Unicode Files

[This is now documented here: https://msdn.microsoft.com/en-us/library/gg318092.aspx ]

Let’s take a look at the function OpenStreamOnFile, which is exported by MAPI. Suppose you want to use this function to open a stream on a file that has a Unicode file name. As has been noted before, this doesn’t work. Why is this? According to the documentation, and according to the header, maputil.h, this function takes two parameters, lpszFileName and lpszPrefix, which are of type LPCTSTR. However, it is impossible for an exported function to take a parameter of this type. Why? Because LPCTSTR is a macro that compiles to either LPCSTR or LPCWSTR depending on whether Unicode was defined in the project. But MAPI’s the same no matter how you compiled your project, so the export won’t change.

In truth, OpenStreamOnFile should have been declared as taking parameters of type LPCSTR. We’re working on an update to the MSDN and to the MAPI Headers to fix that. We’ll also be documenting a new function, which you can go ahead and use to open files with Unicode names: OpenStreamOnFileW. This is the Unicode version of OpenStreamOnFile which takes Unicode strings. Here’s the signature:

 STDMETHODIMP OpenStreamOnFileW(
   LPALLOCATEBUFFER lpAllocateBuffer,
   LPFREEBUFFER lpFreeBuffer,
   ULONG ulFlags,
   __in LPCWSTR lpszFileName,
   __in_opt LPCWSTR lpszPrefix,
   LPSTREAM FAR * lppStream);
typedef HRESULT (STDMETHODCALLTYPE FAR * LPOPENSTREAMONFILEW) (
   LPALLOCATEBUFFER lpAllocateBuffer,
   LPFREEBUFFER lpFreeBuffer,
   ULONG ulFlags,
   __in LPCWSTR lpszFileName,
   __in_opt LPCWSTR lpszPrefix,
   LPSTREAM FAR * lppStream);

Other than the change to the strings, the function is identical to OpenStreamOnFile. Officially, we’re only documenting this function for Outlook 2010 and higher, but the function is also there in Outlook 2003 and 2007. The Exchange MAPI Download does not implement OpenStreamOnFileW at all.

The November build of MFCMAPI is being augmented to handle Unicode file names. Part of that rewrite is that MFCMAPI will use OpenStreamOnFileW if it’s available, and fall back to OpenStreamOnFile if it’s not.

Enjoy!