artsince
artsince

Reputation: 1032

.net c# cannot find img resources when open with exe

My exe processes text documents and I want to be able to right click on documents, select open with and point to my exe file. I can double click on my exe and choose a file to process with OpenFileDialog and it works fine. However, when I do open with, I get FileNotFound error.

Here is the error log:

System.IO.FileNotFoundException: attention.jpg
   at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement)
   at System.Drawing.Image.FromFile(String filename)
   at ImzaDogrulamaUygulamasi.frmCertificate.FillTreeView() in D:\VSS\SOURCE\VS2008\EGA\ImzaDogrulamaUygulamasi\ImzaDogrulamaUygulamasi\frmCertificate.cs:line 76
   at ImzaDogrulamaUygulamasi.frmCertificate.Form2_Load(Object sender, EventArgs e) in D:\VSS\SOURCE\VS2008\EGA\ImzaDogrulamaUygulamasi\ImzaDogrulamaUygulamasi\frmCertificate.cs:line 244
   at System.Windows.Forms.Form.OnLoad(EventArgs e)
   at System.Windows.Forms.Form.OnCreateControl()
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.ContainerControl.WndProc(Message& m)
   at System.Windows.Forms.Form.WmShowWindow(Message& m)
   at System.Windows.Forms.Form.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)

and this is how I add my images in my code, all resources are in the same directory with the exe file:

    ImageList myImageList = new ImageList();

    myImageList.Images.Add(Image.FromFile("attention.jpg"));
    myImageList.Images.Add(Image.FromFile("sandglass.jpg"));
    myImageList.Images.Add(Image.FromFile("11.JPG"));
    myImageList.Images.Add(Image.FromFile("checkGif.jpg"));

    treeView1.ImageList = myImageList;

Any help is much appreciated. Thanks

Upvotes: 1

Views: 1137

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545865

If you choose “Open with” your application is probably opened as running in the same folder as the file you want to open. That is, the execution path of your application is different from the path where the executable is found.

Thus, your file attention.jpg is searched relative to that path, rather than the application path.

To correct this, use:

string appPath = Application.StartupPath;
myImageList.Images.Add(Image.FromFile(Path.Combine(appPath, "attention.jpg")));

Another, perhaps better, alternative would be to use embedded resources via My.Resource instead of relying on separate resource files.

Upvotes: 1

Related Questions