1、嵌入的资源(Embedded Resource)
在VS(Microsoft Visual Studio)中将文件的生成操作设置 "嵌入的资源" 的读取方法,代码如下,
using (Stream stream = Assembly.GetExecutingAs().GetManifestResourceStream("PDF2PPT.Aspose.Total.lic"))
{
string content = new StreamReader(stream).ReadToEnd();
}
2、资源(Resource)
在VS(Microsoft Visual Studio)中将文件的生成操作设置 "Resource" 的读取方法,代码如下,
Stream stream = null;
ResourceManager rm = new ResourceManager("PDF2PPT.g",typeof(Form1).Assembly);
ResourceSet rs = rm.GetResourceSet(new System.Globalization.CultureInfo("en"), true, true);
foreach (DictionaryEntry item in rs)
{
if (item.Key.ToString() == fullname)
stream = item.Value as Stream;
}
using (stream)
{
string content = new StreamReader(stream).ReadToEnd();
}
3、.Resx资源文件
直接添加文件到.Resx资源文件中,在运行时使用Resource Manager读取,代码如下,
1)读取内容
string sTemplate = string.Empty;
Assembly assembly = Assembly.GetExecutingAssembly();
string resourceName = assembly.GetName().Name.ToString() + ".Resources.PageTemplate.html";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader sr = new StreamReader(stream))
{
sTemplate = sr.ReadToEnd();
}
}
2)复制文件
string sDb = AppDomain.CurrentDomain.BaseDirectory + "rec.db";
if (!File.Exists(sDb))
{
Assembly assembly = Assembly.GetExecutingAssembly();
string resourceName = assembly.GetName().Name.ToString() + ".Resources.rec.db";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Seek(0, SeekOrigin.Begin);
using (FileStream fs = new FileStream(sDb, FileMode.Create))
fs.Write(buffer, 0, buffer.Length);
}
Console.WriteLine($"db文件:{sDb},不存在,已自动复制");
}
3)获取资源中的图像文件
Properties.Resources res = new Properties.Resources();
PropertyInfo[] properInfo = res.GetType().GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (PropertyInfo item in properInfo)
{
// 获取指定文件名格式的图片
if (item.Name.Contains("img_"))
{
Bitmap b = (Bitmap)Resources.ResourceManager.GetObject(item.Name, Properties.Resources.Culture);
using (MemoryStream stream = new MemoryStream())
{
b.Save(stream, ImageFormat.Jpeg);
byte[] data = new byte[stream.Length];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(data, 0, Convert.ToInt32(stream.Length));
// do someting..
}
}
}
4)获取资源中的字符串
string sVal = Resources.ResourceManager.GetObject(item.Name);