在C#中,可以通過使用System.Drawing.Icon
類來嵌入和提取圖標文件。以下是一個示例代碼:
using System;
using System.Drawing;
using System.IO;
using System.Reflection;
class Program
{
static void Main()
{
// 讀取圖標文件
Icon icon = new Icon("icon.ico");
// 將圖標文件嵌入到程序集中
using (MemoryStream ms = new MemoryStream())
{
icon.Save(ms);
byte[] iconData = ms.ToArray();
Assembly assembly = Assembly.GetExecutingAssembly();
string resourceName = "icon.ico";
using (Stream resourceStream = assembly.GetManifestResourceStream(resourceName))
{
if (resourceStream == null)
{
using (Stream output = assembly.GetManifestResourceStream(resourceName))
{
output.Write(iconData, 0, iconData.Length);
}
}
}
}
}
}
using System;
using System.Drawing;
using System.IO;
using System.Reflection;
class Program
{
static void Main()
{
// 從程序集中提取圖標文件
Assembly assembly = Assembly.GetExecutingAssembly();
string resourceName = "icon.ico";
using (Stream resourceStream = assembly.GetManifestResourceStream(resourceName))
{
using (MemoryStream ms = new MemoryStream())
{
resourceStream.CopyTo(ms);
Icon icon = new Icon(ms);
// 使用提取的圖標文件
// 例如,將圖標顯示在窗體上
Form form = new Form();
form.Icon = icon;
form.Show();
}
}
}
}
在上面的示例中,首先創建一個Icon
對象,然后將其保存為字節數組,并將其嵌入到程序集中。然后通過程序集中的資源流提取圖標文件,并將其轉換為Icon
對象,最后可以將其用于顯示在窗體上。