我有下面的MAPI類的問題。(原始來源http://www.codeproject.com/KB/IP/SendFileToNET.aspx)試圖讀取或寫入保護內存
當用戶嘗試發送郵件使用SendMailPopup法的電子郵件程序正確打開電子郵件,但郵件窗口後,關閉該程序有時與消息崩潰: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
我懷疑該錯誤是通過清理方法和引起我管理用的Int64存儲在原始使用的指針而不是INT減少撞車的頻率版。然而,我的.NET不安全的編程知識是相當有限,所以有人可以幫助我找出是什麼導致其餘的崩潰
更新:顯然清理方法不會導致異常,因爲即使它被註釋掉程序崩潰,所以唯一可能的原因是MAPI32.ddl sendmail方法。可能有些指針作爲參數傳遞給它。
用戶正在使用具有64位處理器和32位winxp的系統。
更新:
在這個線程提供的解決方案確實降低死機的頻率,但並沒有完全解決問題。唯一能解決問題的解決方案是編寫一個使用C++的小型控制檯應用程序,實際上可以調用MAPI。我們的.NET應用程序通過啓動控制檯應用程序並使用參數向其傳遞數據來與mapi接口。
public class MAPI
{
public bool AddRecipientTo(string email)
{
return AddRecipient(email, HowTo.MAPI_TO);
}
public bool AddRecipientCC(string email)
{
return AddRecipient(email, HowTo.MAPI_CC);
}
public bool AddRecipientBCC(string email)
{
return AddRecipient(email, HowTo.MAPI_BCC);
}
public void AddAttachment(string strAttachmentFileName)
{
m_attachments.Add(strAttachmentFileName);
}
public int SendMailPopup(string strSubject, string strBody)
{
return SendMail(strSubject, strBody, MAPI_LOGON_UI | MAPI_DIALOG);
}
public int SendMailDirect(string strSubject, string strBody)
{
return SendMail(strSubject, strBody, MAPI_LOGON_UI);
}
[DllImport("MAPI32.DLL")]
static extern int MAPISendMail(IntPtr sess, IntPtr hwnd, MapiMessage message, int flg, int rsv);
int SendMail(string strSubject, string strBody, int how)
{
MapiMessage msg = new MapiMessage();
msg.subject = strSubject;
msg.noteText = strBody;
msg.recips = GetRecipients(out msg.recipCount);
msg.files = GetAttachments(out msg.fileCount);
m_lastError = MAPISendMail(new IntPtr(0L), new IntPtr(0L), msg, how, 0);
if (m_lastError > 1)
MessageBox.Show("MAPISendMail failed! " + GetLastError(), "MAPISendMail");
Cleanup(ref msg);
return m_lastError;
}
bool AddRecipient(string email, HowTo howTo)
{
if (!String.IsNullOrEmpty(email))
{
MapiRecipDesc recipient = new MapiRecipDesc();
recipient.recipClass = (int)howTo;
recipient.name = email;
m_recipients.Add(recipient);
return true;
}
else
{
return false;
}
}
IntPtr GetRecipients(out int recipCount)
{
recipCount = 0;
if (m_recipients.Count == 0)
return IntPtr.Zero;
int size = Marshal.SizeOf(typeof(MapiRecipDesc));
IntPtr intPtr = Marshal.AllocHGlobal(m_recipients.Count * size);
int ptr = (int)intPtr;
foreach (MapiRecipDesc mapiDesc in m_recipients)
{
Marshal.StructureToPtr(mapiDesc, (IntPtr)ptr, false);
ptr += size;
}
recipCount = m_recipients.Count;
return intPtr;
}
IntPtr GetAttachments(out int fileCount)
{
fileCount = 0;
if (m_attachments == null)
return IntPtr.Zero;
if ((m_attachments.Count <= 0) || (m_attachments.Count > maxAttachments))
return IntPtr.Zero;
int size = Marshal.SizeOf(typeof(MapiFileDesc));
IntPtr intPtr = Marshal.AllocHGlobal(m_attachments.Count * size);
MapiFileDesc mapiFileDesc = new MapiFileDesc();
mapiFileDesc.position = -1;
int ptr = (int)intPtr;
foreach (string strAttachment in m_attachments)
{
mapiFileDesc.name = Path.GetFileName(strAttachment);
mapiFileDesc.path = strAttachment;
Marshal.StructureToPtr(mapiFileDesc, (IntPtr)ptr, false);
ptr += size;
}
fileCount = m_attachments.Count;
return intPtr;
}
void Cleanup(ref MapiMessage msg)
{
try
{
int size = Marshal.SizeOf(typeof(MapiRecipDesc));
Int64 ptr = 0;
if (msg.recips != IntPtr.Zero)
{
ptr = msg.recips.ToInt64();
for (int i = 0; i < msg.recipCount; i++)
{
Marshal.DestroyStructure((IntPtr)ptr, typeof(MapiRecipDesc));
ptr += size;
}
Marshal.FreeHGlobal(msg.recips);
}
if (msg.files != IntPtr.Zero)
{
size = Marshal.SizeOf(typeof(MapiFileDesc));
ptr = msg.files.ToInt64();
for (int i = 0; i < msg.fileCount; i++)
{
Marshal.DestroyStructure((IntPtr)ptr, typeof(MapiFileDesc));
ptr += size;
}
Marshal.FreeHGlobal(msg.files);
}
m_recipients.Clear();
m_attachments.Clear();
}
catch (Exception e)
{
SmtpSender errorSender = new SmtpSender();
errorSender.SendAutomaticError(e.StackTrace + e.Message, "Virhe mapi sähköpostin lähetyksessä" + MySession.ProjectName + " Käyttäjä:" + MySession.LoginName);
}
}
public string GetLastError()
{
if (m_lastError <= 26)
return errors[m_lastError];
return "MAPI error [" + m_lastError.ToString() + "]";
}
readonly string[] errors = new string[] {
"OK [0]", "User abort [1]", "Yleinen virhe sähköpostin lähettämisessä [2]", "MAPI login failure [3]",
"Disk full [4]", "Insufficient memory [5]", "Access denied [6]", "-unknown- [7]",
"Too many sessions [8]", "Too many files were specified [9]", "Too many recipients were specified [10]", "A specified attachment was not found [11]",
"Attachment open failure [12]", "Attachment write failure [13]", "Unknown recipient [14]", "Bad recipient type [15]",
"No messages [16]", "Invalid message [17]", "Text too large [18]", "Invalid session [19]",
"Type not supported [20]", "A recipient was specified ambiguously [21]", "Message in use [22]", "Network failure [23]",
"Invalid edit fields [24]", "Asiakkaalle ei ole määritetty sähköpostiosoitetta.", "Not supported [26]"
};
List<MapiRecipDesc> m_recipients = new List<MapiRecipDesc>();
List<string> m_attachments = new List<string>();
int m_lastError = 0;
const int MAPI_LOGON_UI = 0x00000001;
const int MAPI_DIALOG = 0x00000008;
const int maxAttachments = 20;
enum HowTo { MAPI_ORIG = 0, MAPI_TO, MAPI_CC, MAPI_BCC };
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiMessage
{
public int reserved;
public string subject;
public string noteText;
public string messageType;
public string dateReceived;
public string conversationID;
public int flags;
public IntPtr originator;
public int recipCount;
public IntPtr recips;
public int fileCount;
public IntPtr files;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiFileDesc
{
public int reserved;
public int flags;
public int position;
public string path;
public string name;
public IntPtr type;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiRecipDesc
{
public int reserved;
public int recipClass;
public string name;
public string address;
public int eIDSize;
public IntPtr entryID;
}
下面是異常的堆棧跟蹤。部分是芬蘭語,但您仍然可以從中看到方法名稱。
kohteessa System.Windows.Forms.UnsafeNativeMethods.DispatchMessageA(MSG& msg) kohteessa System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) kohteessa System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) kohteessa System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) kohteessa System.Windows.Forms.Application.Run(Form mainForm)
這是一個'稍微'更有趣的版本。請注意,您應該查看一些很小的更改。 http://pastebin.com/5P0bYEJj – Tergiver 2010-11-16 17:37:47
這大大減少了異常的數量,但有時還會出現異常。 – Jargo 2010-11-29 12:43:38
@Jargo:我修改了上面的代碼,將Joerg關於增加文件附件路徑緩衝區的建議結合起來。 – Tergiver 2010-11-29 15:27:30