GDI + Exception when using DrawString ()

I get an error when trying to create a barcode image using a barcode font. This happens in production, but not in dev.

Barcode Method:

/// <summary>
/// Create a barcode image by writing out a string using a barcode font and save it
/// </summary>
/// <param name="barcodeText">The text string of the barcode</param>
/// <param name="saveLocation">Where to save the file to</param>
/// <param name="font">The barcode font</param>
/// <param name="imageFormat">The image format</param>
private void CreateBarcodeImage(string barcodeText, string saveLocation, System.Drawing.Font font, ImageFormat imageFormat)
{
    // Draw the barcode image
    using (Bitmap bmp = new Bitmap(500, 75))
    {
    try
    {
        using (Graphics g = Graphics.FromImage(bmp))
        {
        g.Clear(_backgroundColour);
        g.DrawString(barcodeText, font, _foregroundBrush, 10, 0);
        bmp.Save(saveLocation, imageFormat);
        g.Dispose();
        }
    }
    catch (Exception ex)
    {
        Log.ErrorException("Exception in LabelPrinter.CreateBarcodeImage()", ex);
        throw;
    }
    }
}

This code is called in a loop since several barcodes are required. In the dev environment, it works fine, but in real time (in Win XP Pro using .net 3.5 SP1 in the winforms application) 2 barcodes are generated, and an exception occurs for the third time.

The exception is trace and stack trace:

An unhandled exception has occurred Attempted to read or write protected memory. This is often an indication that other memory is corrupt. 
at System.Drawing.SafeNativeMethods.Gdip.GdipMeasureString(HandleRef graphics, String textString, Int32 length, HandleRef font, GPRECTF& layoutRect, HandleRef stringFormat, GPRECTF& boundingBox, Int32& codepointsFitted, Int32& linesFilled) 
at System.Drawing.Graphics.MeasureString(String text, Font font, SizeF layoutArea, StringFormat stringFormat) 
at System.Drawing.Graphics.MeasureString(String text, Font font) 
at Srcl.WasteTrak.Gui.Documents.LabelPrinter.CreateBarcodeImage(String barcodeText, String saveLocation, Font font, ImageFormat imageFormat) 
in c:\scc\SRCL\SRCL.WasteTrak\SRCL.WasteTrak.Gui\Documents\LabelPrinter.cs:line 60 

I can’t find out what causes the problem, but from a Google search this calls to unmanaged code causes it, but I did not find a solution.

Is anyone

+3
1

g.Dispose();

.

0

Source: https://habr.com/ru/post/1711582/


All Articles