Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Drawing.Icon constructor throwing "Operation completed successfully" exception

On a Windows XP machine, the following code is throwing a System.ComponentModel.Win32Exception with the message "The operation completed successfully"

System.Drawing.Icon icon = new System.Drawing.Icon("icon.ico");

I can stop the program crashing with

try
{
    System.Drawing.Icon icon = new System.Drawing.Icon("icon.ico");
}
catch(System.ComponentModel.Win32Exception ex)
{
    if (ex.NativeErrorCode != 0)
    {
        throw;
    }
}

but of course the icon is not set.

The full stack trace is

at System.Drawing.Icon.Initialize(Int32 width, Int32 height)
at System.Drawing.Icon..ctor(String fileName, Int32 width, Int32 height)
at System.Drawing.Icon..ctor(String fileName)
at hermes.Window1..ctor() in D:\\projects\\hermesclient\\hermesWPF\\hermes\\Window1.xaml.cs:line 50"

That line 50 is the original line I posted.

This is a WPF app, and on a Windows 7 machine the code works fine.

EDIT: Turned out the icon wasn't working in Windows XP at all, adding 256 colour versions seems to have fixed it.

like image 422
jonnystoten Avatar asked Oct 14 '22 09:10

jonnystoten


2 Answers

From the looks of it the problem seems to be an issue with not disposing with objects properly. It's hard to pin point exactly where the issue in your case is occurring but as a general rule of thumb make sure you implement the using directive when dealing with objects that implement IDisposable.

Even in the sample you have provided try doing something like:

using (var icon = new System.Drawing.Icon("icon.ico"))
{
    // use icon
}
// icon is then disposed.

Have a read of this article.

like image 63
James Avatar answered Nov 03 '22 00:11

James


Does the file icon1.ico exists in the same directory as the .NET executable? You did not say explicitly...are you reading this as an external icon file? perhaps this

string sPath2Icon = Path.Combine(Environment.CurrentDirectory, "icon1.ico");
using (System.Drawing.Icon icon = new System.Drawing.Icon(sPath2Icon)){
    // Do what you have to do with icon!
}

Hope this helps, Best regards, Tom.

like image 38
t0mm13b Avatar answered Nov 02 '22 22:11

t0mm13b