private string GetTextFromCommonDialog(IntPtr hWnd, uint msg) { string str = null; IntPtr buffer = Marshal.AllocCoTaskMem(2 * InteropUtil.NumberOfFileChars); try { InteropUtil.SendMessageIntPtr(hWnd, msg, new IntPtr(InteropUtil.NumberOfFileChars), buffer); var chars = new char[InteropUtil.NumberOfFileChars]; Marshal.Copy(buffer, chars, 0, chars.Length); int firstZeroTerm = ((IList)chars).IndexOf('\0'); if (firstZeroTerm >= 0 && firstZeroTerm <= chars.Length - 1) { str = new string(chars, 0, firstZeroTerm); } } finally { Marshal.FreeCoTaskMem(buffer); } return(str); }