I am using .NET 2.0 VS2005. I am writing a network application to allow users from other PC to talk to my application (running at my PC) to print through my printer driver.
I got this runtime exception:
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at PrintGateway.PrintEngine.OpenPrinter(String szPrinter, IntPtr& hPrinter, IntPtr pd)
at PrintGateway.PrintEngine.SendBytesToPrinter(Int32 flag, String szPrinterName, String docname, IntPtr pBytes, Int32 dwCount) in E:\PrintGateway\PrintEngine.cs:line 70
at PrintGateway.PrintEngine.SendStringToPrinter(String szPrinterName, String docname, String szString) in E:\PrintGateway\PrintEngine.cs:line 167
Below is my code where this exception happens. Please help me. Thanks and best regards.
public static bool SendStringToPrinter(string szPrinterName,
string docname,
string szString)
{
IntPtr pBytes = new IntPtr();
try
{
// Assume that the printer is expecting ANSI text, and then convert
// the string to ANSI text
pBytes = Marshal.StringToCoTaskMemAnsi(szString);
Byte[] encodedBytes = Encoding.UTF8.GetBytes(szString);
Marshal.Copy(encodedBytes, 0, pBytes, encodedBytes.Length);
// Send the converted ANSI string to the printer.
SendBytesToPrinter(0, szPrinterName, docname, pBytes, encodedBytes.Length);
}
catch (Exception ex)
{
log.Error("Printing Exception : " + ex);
}
finally
{
Marshal.FreeCoTaskMem(pBytes);
}
return true;
}
// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
public static bool SendBytesToPrinter(string szPrinterName,
string docname, IntPtr pBytes, Int32 dwCount)
{
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; // Assume failure unless you specifically succeed.
di.pDocName = docname;
di.pDataType = "RAW";
// Open the printer.
if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
{
if ( StartDocPrinter(hPrinter, 1, di))
{
if ( StartPagePrinter(hPrinter))
{
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if (bSuccess == false)
{
dwError = Marshal.GetLastWin32Error();
}
return bSuccess;
}