Page Top

C# 资源Resources.resx中文件的获取、读取、复制与遍历

1、添加文件,并设置文件生成操作

 2、读取内容

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();
   }
}

 

3、复制文件

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},不存在,已自动复制");
}

 

4、遍历文件

(1)获取资源中的图像文件

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..
        }
    }
}

(2)获取资源中的字符串

..
string sVal = Resources.ResourceManager.GetObject(item.Name);
..

好记性不如烂笔头。

posted @ 2021-01-27 10:50  抹茶大虾球丶  阅读(5049)  评论(0编辑  收藏  举报