简体   繁体   English

C#程式当机(.ico档案)

[英]C# program crash (.ico file)

The program crashes if there's no .ico file inside the same folder. 如果同一文件夹中没有.ico文件,则程序崩溃。 I have: 我有:

  1. Added the MyIcon.ico file in the Application section, also 'embed manifest with default settings' is checked. 在“应用程序”部分添加了MyIcon.ico文件,还选中了“使用默认设置嵌入清单”。
  2. Made the .ico file as Embedded Resource (Build Action) in the .ico file properties. 在.ico文件属性中将.ico文件设置为嵌入式资源(生成操作)。
  3. Added this.Icon = new Icon("plat.ico"); 添加了this.Icon = new Icon("plat.ico"); in the Public form. 以公开形式。

So... why is the application not booting? 那么...为什么应用程序无法启动? What gives? 是什么赋予了?

The constructor for Icon you are using tries to read "plat.ico" as a filename, not from embedded resources. 您正在使用的Icon构造函数尝试读取“ plat.ico”作为文件名,而不是从嵌入式资源中读取。

If you want to load the Icon from resources, you will need to explicitly get a Stream from the resource, then pass that into the Icon's constructor. 如果要从资源加载Icon,则需要从资源显式获取Stream ,然后将其传递给Icon的构造函数。

This will likely be something similar to: 这可能类似于:

// Add using System.Reflection; at the top of your file...

this.Icon = new Icon(
    Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace.plat.ico")
  );

Alternatively, you can use the constructor overload that pulls directly from a resource, by name, instead of a filename: 另外,您可以使用构造函数重载 ,该重载直接从资源中提取名称而不是文件名:

this.Icon = new Icon(this.GetType(), "plat.ico");

I had the same problem in a windows form, where the icon could not be found even though it was in the same directory as the form. 我在Windows窗体中遇到了同样的问题,即使它与窗体位于同一目录,也找不到图标。

notifyIcon1.Icon = new Icon("enabled.ico");

I looked at the .ico file's properties in VS2010 and saw that Copy to Output Directory was set to Do not copy . 我查看了VS2010中.ico文件的属性,发现将“ 复制到输出目录”设置为“不复制” I changed it to Copy always and that did the trick. 我将其始终更改为“ 复制” ,并且达到了目的。

Sometimes the simplest solution is the best solution. 有时,最简单的解决方案就是最好的解决方案。

您需要将图标文件的“复制到输出”设置为“始终复制”或“如果更新则复制”。

You are invoking wrong constructor. 您正在调用错误的构造函数。 Just use this: 只需使用此:

this.Icon = new Icon(this.GetType(), "plat.ico");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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