简体   繁体   中英

.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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM