c# - 是否有更简单的语法来访问程序集中嵌入的资源?

标签 c# .net .net-4.0

现在我在类里面有几个:

string upgrade_file 
    = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(
        Assembly.GetExecutingAssembly().GetName().Name 
        + ".schemas.template.db_upgrades.txt")
        ).ReadToEnd();

我可以编写一个包装函数来简化对嵌入式资源的访问(如果必须的话,我会这样做),但是有没有更简单或更优雅的方法来使用 .Net 本地访问它们?

例如,我发现 GetManifestResourceStream(...) 不是静态的很奇怪。另一个例子:是否有一些方法返回字符串而不是文本文件的流?

更新 1:

明确地说,我在子目录中有文本文件,我想要:

  1. 这些文件仍然是单独的文件(例如,能够分别对它们进行源代码控制)
  2. 这些文件保持嵌入资源,即与程序集一起编译。

现在我正在这样做,如图所示: enter image description here

更新 2:

我没有设法使用答案中的任何内容来简化对文件的访问。

这是我现在使用的辅助方法,以防其他人发现它有用:

/// <summary>
/// Get the content of a text file embedded in the enclosing assembly.
/// </summary>
/// <param name="resource">The "path" to the text file in the format 
/// (e.g. subdir1.subdir2.thefile.txt)</param>
/// <returns>The file content</returns>
static string GetEmbeddedTextFile(string resource)
{
    return new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(
        Assembly.GetExecutingAssembly().GetName().Name + "." + resource)).ReadToEnd();
}

最佳答案

我的项目中有一个名为 Resource1 的资源文件,其中包含一个 TXT 文件和一个二进制文件。
我能做到

string str = Resource1.TxtFile;
byte[] file = Resource1.BinaryFile;

关于c# - 是否有更简单的语法来访问程序集中嵌入的资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10131987/

相关文章:

c# - 创建数组与列表

c# - XML/XHTML 替换内容?

c# - 无法在数据模板内设置 CommandBinding

C# 调试 - 在不知道哪个属性具有它的情况下寻找某个值

Windows 窗体用户控件中的 C# 按键监听器

c# - 如何生成唯一的 12 位字母数字 key 以用于 URL

c# - BitmapImage 为 PixelWidth 和 PixelHeight 返回 0

.net - 在高负载的 .ashx http 处理程序中将记录附加到磁盘文件的最快、最安全的方法是什么?

c# - String.Concat 低效代码?

.NET - 数据集是 IEnumerable 的派生物?