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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With