如何读取嵌入的资源文本文件

发布于 2024-09-11 05:11:55 字数 790 浏览 9 评论 0原文

如何使用 StreamReader 读取嵌入资源(文本文件)并将其作为字符串返回?我当前的脚本使用 Windows 窗体和文本框,允许用户查找和替换未嵌入的文本文件中的文本。

private void button1_Click(object sender, EventArgs e)
{
    StringCollection strValuesToSearch = new StringCollection();
    strValuesToSearch.Add("Apple");
    string stringToReplace;
    stringToReplace = textBox1.Text;

    StreamReader FileReader = new StreamReader(@"C:\MyFile.txt");
    string FileContents;
    FileContents = FileReader.ReadToEnd();
    FileReader.Close();
    foreach (string s in strValuesToSearch)
    {
        if (FileContents.Contains(s))
            FileContents = FileContents.Replace(s, stringToReplace);
    }
    StreamWriter FileWriter = new StreamWriter(@"MyFile.txt");
    FileWriter.Write(FileContents);
    FileWriter.Close();
}

How do I read an embedded resource (text file) using StreamReader and return it as a string? My current script uses a Windows form and textbox that allows the user to find and replace text in a text file that is not embedded.

private void button1_Click(object sender, EventArgs e)
{
    StringCollection strValuesToSearch = new StringCollection();
    strValuesToSearch.Add("Apple");
    string stringToReplace;
    stringToReplace = textBox1.Text;

    StreamReader FileReader = new StreamReader(@"C:\MyFile.txt");
    string FileContents;
    FileContents = FileReader.ReadToEnd();
    FileReader.Close();
    foreach (string s in strValuesToSearch)
    {
        if (FileContents.Contains(s))
            FileContents = FileContents.Replace(s, stringToReplace);
    }
    StreamWriter FileWriter = new StreamWriter(@"MyFile.txt");
    FileWriter.Write(FileContents);
    FileWriter.Close();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

凉薄对峙 2024-09-18 05:11:56

您可以使用 程序集.GetManifestResourceStream方法

  1. 添加以下用法

     使用 System.IO;
     使用系统反射;
    
  2. 设置相关文件的属性:
    参数Build Action,值为Embedded Resource

  3. 使用以下代码

     var assembly = Assembly.GetExecutingAssembly();
     var 资源名称 = "MyCompany.MyProduct.MyFile.txt";
    
     使用 (Stream 流 = assembly.GetManifestResourceStream(resourceName))
     使用 (StreamReader reader = new StreamReader(stream))
     {
         字符串结果 = reader.ReadToEnd();
     }
    

    resourceName程序集 中嵌入的资源之一的名称。
    例如,如果您嵌入一个名为 "MyFile.txt" 的文本文件,该文件位于默认命名空间 "MyCompany.MyProduct" 的项目根目录中,则 resourceName“MyCompany.MyProduct.MyFile.txt”
    您可以使用 获取程序集中所有资源的列表Assembly.GetManifestResourceNames方法


仅从文件名中获取 resourceName (绕过命名空间内容)是一个简单的技巧:

string resourceName = assembly.GetManifestResourceNames()
  .Single(str => str.EndsWith("YourFileName.txt"));

完整的示例:

public string ReadResource(string name)
{
    // Determine path
    var assembly = Assembly.GetExecutingAssembly();
    string resourcePath = name;
    // Format: "{Namespace}.{Folder}.{filename}.{Extension}"
    if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
    {
        resourcePath = assembly.GetManifestResourceNames()
            .Single(str => str.EndsWith(name));
    }

    using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
    using (StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

或作为异步扩展方法:

internal static class AssemblyExtensions
{
    public static async Task<string> ReadResourceAsync(this Assembly assembly, string name)
    {
        // Determine path
        string resourcePath = name;
        // Format: "{Namespace}.{Folder}.{filename}.{Extension}"
        if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
        {
            resourcePath = assembly.GetManifestResourceNames()
                .Single(str => str.EndsWith(name));
        }

        using Stream stream = assembly.GetManifestResourceStream(resourcePath)!;
        using StreamReader reader = new(stream);
        return await reader.ReadToEndAsync();
    }
}

// Usage
string resourceText = await Assembly.GetExecutingAssembly().ReadResourceAsync("myResourceName");

You can use the Assembly.GetManifestResourceStream Method:

  1. Add the following usings

     using System.IO;
     using System.Reflection;
    
  2. Set property of relevant file:
    Parameter Build Action with value Embedded Resource

  3. Use the following code

     var assembly = Assembly.GetExecutingAssembly();
     var resourceName = "MyCompany.MyProduct.MyFile.txt";
    
     using (Stream stream = assembly.GetManifestResourceStream(resourceName))
     using (StreamReader reader = new StreamReader(stream))
     {
         string result = reader.ReadToEnd();
     }
    

    resourceName is the name of one of the resources embedded in assembly.
    For example, if you embed a text file named "MyFile.txt" that is placed in the root of a project with default namespace "MyCompany.MyProduct", then resourceName is "MyCompany.MyProduct.MyFile.txt".
    You can get a list of all resources in an assembly using the Assembly.GetManifestResourceNames Method.


A no brainer astute to get the resourceName from the file name only (by pass the namespace stuff):

string resourceName = assembly.GetManifestResourceNames()
  .Single(str => str.EndsWith("YourFileName.txt"));

A complete example:

public string ReadResource(string name)
{
    // Determine path
    var assembly = Assembly.GetExecutingAssembly();
    string resourcePath = name;
    // Format: "{Namespace}.{Folder}.{filename}.{Extension}"
    if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
    {
        resourcePath = assembly.GetManifestResourceNames()
            .Single(str => str.EndsWith(name));
    }

    using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
    using (StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

or as an async extension method:

internal static class AssemblyExtensions
{
    public static async Task<string> ReadResourceAsync(this Assembly assembly, string name)
    {
        // Determine path
        string resourcePath = name;
        // Format: "{Namespace}.{Folder}.{filename}.{Extension}"
        if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
        {
            resourcePath = assembly.GetManifestResourceNames()
                .Single(str => str.EndsWith(name));
        }

        using Stream stream = assembly.GetManifestResourceStream(resourcePath)!;
        using StreamReader reader = new(stream);
        return await reader.ReadToEndAsync();
    }
}

// Usage
string resourceText = await Assembly.GetExecutingAssembly().ReadResourceAsync("myResourceName");
飞烟轻若梦 2024-09-18 05:11:56

您可以使用两种不同的方法将文件添加为资源。

访问该文件所需的 C# 代码有所不同,具体取决于最初添加文件所使用的方法。

方法 1:添加现有文件,将属性设置为 Embedded Resource

将文件添加到您的项目,然后将类型设置为 Embedded Resource

注意:如果您使用此方法添加文件,则可以使用 GetManifestResourceStream 来访问它(请参阅 来自@dtb的回答)。

在此处输入图像描述

方法2:将文件添加到Resources.resx

打开Resources.resx 文件,使用下拉框添加文件,将Access Modifier 设置为public

注意:如果使用此方法添加文件,则可以使用 Properties.Resources 来访问它(请参阅 @Night Walker 的回答)。

在此处输入图像描述

You can add a file as a resource using two separate methods.

The C# code required to access the file is different, depending on the method used to add the file in the first place.

Method 1: Add existing file, set property to Embedded Resource

Add the file to your project, then set the type to Embedded Resource.

NOTE: If you add the file using this method, you can use GetManifestResourceStream to access it (see answer from @dtb).

enter image description here

Method 2: Add file to Resources.resx

Open up the Resources.resx file, use the dropdown box to add the file, set Access Modifier to public.

NOTE: If you add the file using this method, you can use Properties.Resources to access it (see answer from @Night Walker).

enter image description here

如日中天 2024-09-18 05:11:56

基本上,您使用 System.Reflection 来获取对当前程序集的引用。然后,您使用GetManifestResourceStream()

例如,来自我发布的页面:

注意:需要添加 using System.Reflection; 才能正常工作

   Assembly _assembly;
   StreamReader _textStreamReader;

   try
   {
      _assembly = Assembly.GetExecutingAssembly();
      _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("MyNamespace.MyTextFile.txt"));
   }
   catch
   {
      MessageBox.Show("Error accessing resources!");
   }

Basically, you use System.Reflection to get a reference to the current Assembly. Then, you use GetManifestResourceStream().

Example, from the page I posted:

Note: need to add using System.Reflection; for this to work

   Assembly _assembly;
   StreamReader _textStreamReader;

   try
   {
      _assembly = Assembly.GetExecutingAssembly();
      _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("MyNamespace.MyTextFile.txt"));
   }
   catch
   {
      MessageBox.Show("Error accessing resources!");
   }
深白境迁sunset 2024-09-18 05:11:56

在 Visual Studio 中,您可以通过项目属性的“资源”选项卡(本例中为“分析”)直接嵌入对文件资源的访问。
Visual Studio 屏幕截图 - 资源选项卡

则可以将生成的文件作为字节数组进行访问

byte[] jsonSecrets = GoogleAnalyticsExtractor.Properties.Resources.client_secrets_reporter;

如果您需要将其作为流, ,然后(来自 https://stackoverflow.com/a/4736185/432976

Stream stream = new MemoryStream(jsonSecrets)

In Visual Studio you can directly embed access to a file resource via the Resources tab of the Project properties ("Analytics" in this example).
visual studio screen shot - Resources tab

The resulting file can then be accessed as a byte array by

byte[] jsonSecrets = GoogleAnalyticsExtractor.Properties.Resources.client_secrets_reporter;

Should you need it as a stream, then ( from https://stackoverflow.com/a/4736185/432976 )

Stream stream = new MemoryStream(jsonSecrets)
心奴独伤 2024-09-18 05:11:56

将文件添加到资源时,您应该选择其访问修饰符为公共,而不是可以进行如下操作。

byte[] clistAsByteArray = Properties.Resources.CLIST01;

CLIST01 是嵌入文件的名称。

实际上你可以去resources.Designer.cs看看getter的名字是什么。

When you added the file to the resources, you should select its Access Modifiers as public than you can make something like following.

byte[] clistAsByteArray = Properties.Resources.CLIST01;

CLIST01 is the name of the embedded file.

Actually you can go to the resources.Designer.cs and see what is the name of the getter.

极致的悲 2024-09-18 05:11:56

添加例如Testfile.sql
项目菜单 ->属性->资源->添加现有文件

    string queryFromResourceFile = Properties.Resources.Testfile.ToString();

在此输入图像描述

adding e.g. Testfile.sql
Project Menu -> Properties -> Resources -> Add Existing file

    string queryFromResourceFile = Properties.Resources.Testfile.ToString();

enter image description here

面如桃花 2024-09-18 05:11:56

我知道这是一个旧线程,但这对我有用:

  1. 将文本文件添加到项目资源中,
  2. 将访问修饰符设置为公共,如安德鲁·希尔上面所示
  3. 阅读如下文本:

    textBox1 = new TextBox();
    textBox1.Text = Properties.Resources.SomeText;
    

我添加到资源中的文本:'SomeText.txt'

I know it is an old thread, but this is what worked for me :

  1. add the text file to the project resources
  2. set the access modifier to public, as showed above by Andrew Hill
  3. read the text like this :

    textBox1 = new TextBox();
    textBox1.Text = Properties.Resources.SomeText;
    

The text that I added to the resources: 'SomeText.txt'

昔梦 2024-09-18 05:11:56

我刚才了解到的是,你的文件不允许有“.”。文件名中的(点)。

文件名中的“.”不好。

Templates.plainEmailBodyTemplate-en.txt -->有效!!!
Templates.plainEmailBodyTemplate.en.txt -->无法通过 GetManifestResourceStream() 工作

可能是因为框架对名称空间与文件名感到困惑......

Something I learned just now is that your file is not allowed to have a "." (dot) in the filename.

A "." in filename is no good.

Templates.plainEmailBodyTemplate-en.txt --> Works!!!
Templates.plainEmailBodyTemplate.en.txt --> doesn't work via GetManifestResourceStream()

Probably because the framework gets confused over namespaces vs filename...

清风不识月 2024-09-18 05:11:56

您还可以使用@dtb 答案的简化版本:

public string GetEmbeddedResource(string ns, string res)
{
    using (var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format("{0}.{1}", ns, res))))
    {
        return reader.ReadToEnd();
    }
}

You can also use this simplified version of @dtb's answer:

public string GetEmbeddedResource(string ns, string res)
{
    using (var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format("{0}.{1}", ns, res))))
    {
        return reader.ReadToEnd();
    }
}
晚风撩人 2024-09-18 05:11:56

通过综合您的所有力量,我使用此帮助程序类以通用方式从任何程序集和任何命名空间读取资源。

public class ResourceReader
{
    public static IEnumerable<string> FindEmbededResources<TAssembly>(Func<string, bool> predicate)
    {
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return
            GetEmbededResourceNames<TAssembly>()
                .Where(predicate)
                .Select(name => ReadEmbededResource(typeof(TAssembly), name))
                .Where(x => !string.IsNullOrEmpty(x));
    }

    public static IEnumerable<string> GetEmbededResourceNames<TAssembly>()
    {
        var assembly = Assembly.GetAssembly(typeof(TAssembly));
        return assembly.GetManifestResourceNames();
    }

    public static string ReadEmbededResource<TAssembly, TNamespace>(string name)
    {
        if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
        return ReadEmbededResource(typeof(TAssembly), typeof(TNamespace), name);
    }

    public static string ReadEmbededResource(Type assemblyType, Type namespaceType, string name)
    {
        if (assemblyType == null) throw new ArgumentNullException(nameof(assemblyType));
        if (namespaceType == null) throw new ArgumentNullException(nameof(namespaceType));
        if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));

        return ReadEmbededResource(assemblyType, $"{namespaceType.Namespace}.{name}");
    }

    public static string ReadEmbededResource(Type assemblyType, string name)
    {
        if (assemblyType == null) throw new ArgumentNullException(nameof(assemblyType));
        if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));

        var assembly = Assembly.GetAssembly(assemblyType);
        using (var resourceStream = assembly.GetManifestResourceStream(name))
        {
            if (resourceStream == null) return null;
            using (var streamReader = new StreamReader(resourceStream))
            {
                return streamReader.ReadToEnd();
            }
        }
    }
}

By all your powers combined I use this helper class for reading resources from any assembly and any namespace in a generic way.

public class ResourceReader
{
    public static IEnumerable<string> FindEmbededResources<TAssembly>(Func<string, bool> predicate)
    {
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return
            GetEmbededResourceNames<TAssembly>()
                .Where(predicate)
                .Select(name => ReadEmbededResource(typeof(TAssembly), name))
                .Where(x => !string.IsNullOrEmpty(x));
    }

    public static IEnumerable<string> GetEmbededResourceNames<TAssembly>()
    {
        var assembly = Assembly.GetAssembly(typeof(TAssembly));
        return assembly.GetManifestResourceNames();
    }

    public static string ReadEmbededResource<TAssembly, TNamespace>(string name)
    {
        if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
        return ReadEmbededResource(typeof(TAssembly), typeof(TNamespace), name);
    }

    public static string ReadEmbededResource(Type assemblyType, Type namespaceType, string name)
    {
        if (assemblyType == null) throw new ArgumentNullException(nameof(assemblyType));
        if (namespaceType == null) throw new ArgumentNullException(nameof(namespaceType));
        if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));

        return ReadEmbededResource(assemblyType, $"{namespaceType.Namespace}.{name}");
    }

    public static string ReadEmbededResource(Type assemblyType, string name)
    {
        if (assemblyType == null) throw new ArgumentNullException(nameof(assemblyType));
        if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));

        var assembly = Assembly.GetAssembly(assemblyType);
        using (var resourceStream = assembly.GetManifestResourceStream(name))
        {
            if (resourceStream == null) return null;
            using (var streamReader = new StreamReader(resourceStream))
            {
                return streamReader.ReadToEnd();
            }
        }
    }
}
萤火眠眠 2024-09-18 05:11:56

我知道这已经过时了,但我只是想指出NETMF(.Net MicroFramework),您可以轻松地做到这一点:

string response = Resources.GetString(Resources.StringResources.MyFileName);

因为NETMF< /em> 没有 GetManifestResourceStream

I know this is old, but I just wanted to point out for NETMF (.Net MicroFramework), you can easily do this:

string response = Resources.GetString(Resources.StringResources.MyFileName);

Since NETMF doesn't have GetManifestResourceStream

橙味迷妹 2024-09-18 05:11:56

某些 VS .NET 项目类型不会自动生成 .NET (.resx) 文件。以下步骤将资源文件添加到您的项目中:

  1. 右键单击​​项目节点并选择添加/新项目,滚动到资源文件。在“名称”框中选择适当的名称,例如“资源”,然后单击“添加”按钮。
  2. 资源文件 Resources.resx 已添加到项目中,并且可以视为解决方案资源管理器中的节点。
  3. 实际上,创建了两个文件,还有一个自动生成的 C# 类 Resources.Designer.cs。不要编辑它,它是由 VS 维护的。该文件包含一个名为 Resources 的类。

现在您可以添加文本文件作为资源,例如 xml 文件:

  1. 双击 Resources.resx。选择添加资源>添加现有文件并滚动到要包含的文件。保留“访问修改”的默认值“内部”。
  2. 图标代表新的资源项。如果选择,属性窗格将显示其属性。对于 xml 文件,在属性编码下选择 Unicode (UTF-8) – 代码页 65001,而不是默认的本地代码页。对于其他文本文件,请选择该文件的正确编码,例如代码页 1252。
  3. 对于 xml 文件等文本文件,Resources 类具有一个名为 string 类型的属性在包含的文件之后。如果文件名为 RibbonManifest.xml,则该属性的名称应为 RibbonManifest。您可以在代码文件 Resources.Designer.cs 中找到确切的名称。
  4. 像任何其他字符串属性一样使用字符串属性,例如:string xml = Resources.RibbonManifest。一般形式为ResourceFileName.IncludedTextFileName。不要使用 ResourceManager.GetString,因为字符串属性的 get 函数已经完成了该操作。

Some VS .NET project types don’t auto-generate a .NET (.resx) file. The following steps add a Resource file to your project:

  1. Right-click the project node and select Add/New Item, scroll to Resources File. In the Name box choose an appropriate name, for instance Resources and click the button Add.
  2. The resource file Resources.resx is added to the project and can be seen as a node in the solution explorer.
  3. Actually, two files are created, there is also an auto-generated C# class Resources.Designer.cs. Don’t edit it, it is maintained by VS. The file contains a class named Resources.

Now you can add a text file as a resource, for example an xml file:

  1. Double-click Resources.resx. Select Add Resource > Add Existing File and scroll to the file you want to be included. Leave the default value Internal for Access Modify.
  2. An icon represents the new resource item. If selected, the property pane shows its properties. For xml files, under the property Encoding select Unicode (UTF-8) – Codepage 65001 instead of the default local codepage. For other text files select the correct encoding of this file, for example codepage 1252.
  3. For text files like xml files, the class Resources has a property of type string that is named after the included file. If the file name is e.g. RibbonManifest.xml, then the property should have the name RibbonManifest. You find the exact name in the code file Resources.Designer.cs.
  4. Use the string property like any other string property, for example: string xml = Resources.RibbonManifest. The general form is ResourceFileName.IncludedTextFileName. Don’t use ResourceManager.GetString since the get-function of the string property has done that already.
邮友 2024-09-18 05:11:56

我读了一个嵌入式资源文本文件使用:

    /// <summary>
    /// Converts to generic list a byte array
    /// </summary>
    /// <param name="content">byte array (embedded resource)</param>
    /// <returns>generic list of strings</returns>
    private List<string> GetLines(byte[] content)
    {
        string s = Encoding.Default.GetString(content, 0, content.Length - 1);
        return new List<string>(s.Split(new[] { Environment.NewLine }, StringSplitOptions.None));
    }

示例:

var template = GetLines(Properties.Resources.LasTemplate /* resource name */);

template.ForEach(ln =>
{
    Debug.WriteLine(ln);
});

I read an embedded resource text file use:

    /// <summary>
    /// Converts to generic list a byte array
    /// </summary>
    /// <param name="content">byte array (embedded resource)</param>
    /// <returns>generic list of strings</returns>
    private List<string> GetLines(byte[] content)
    {
        string s = Encoding.Default.GetString(content, 0, content.Length - 1);
        return new List<string>(s.Split(new[] { Environment.NewLine }, StringSplitOptions.None));
    }

Sample:

var template = GetLines(Properties.Resources.LasTemplate /* resource name */);

template.ForEach(ln =>
{
    Debug.WriteLine(ln);
});
别再吹冷风 2024-09-18 05:11:56

阅读此处发布的所有解决方案后。这就是我解决它的方法:

// How to embedded a "Text file" inside of a C# project
//   and read it as a resource from c# code:
//
// (1) Add Text File to Project.  example: 'myfile.txt'
//
// (2) Change Text File Properties:
//      Build-action: EmbeddedResource
//      Logical-name: myfile.txt      
//          (note only 1 dot permitted in filename)
//
// (3) from c# get the string for the entire embedded file as follows:
//
//     string myfile = GetEmbeddedResourceFile("myfile.txt");

public static string GetEmbeddedResourceFile(string filename) {
    var a = System.Reflection.Assembly.GetExecutingAssembly();
    using (var s = a.GetManifestResourceStream(filename))
    using (var r = new System.IO.StreamReader(s))
    {
        string result = r.ReadToEnd();
        return result;
    }
    return "";      
}

After reading all the solutions posted here. This is how I solved it:

// How to embedded a "Text file" inside of a C# project
//   and read it as a resource from c# code:
//
// (1) Add Text File to Project.  example: 'myfile.txt'
//
// (2) Change Text File Properties:
//      Build-action: EmbeddedResource
//      Logical-name: myfile.txt      
//          (note only 1 dot permitted in filename)
//
// (3) from c# get the string for the entire embedded file as follows:
//
//     string myfile = GetEmbeddedResourceFile("myfile.txt");

public static string GetEmbeddedResourceFile(string filename) {
    var a = System.Reflection.Assembly.GetExecutingAssembly();
    using (var s = a.GetManifestResourceStream(filename))
    using (var r = new System.IO.StreamReader(s))
    {
        string result = r.ReadToEnd();
        return result;
    }
    return "";      
}
攒眉千度 2024-09-18 05:11:56

您可能会发现这个类非常方便从当前的Assembly读取嵌入的资源文件:

using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;

public static class EmbeddedResourceUtils
{
    public static string ReadFromResourceFile(string endingFileName)
    {
        var assembly = Assembly.GetExecutingAssembly();
        var manifestResourceNames = assembly.GetManifestResourceNames();

        foreach (var resourceName in manifestResourceNames)
        {
            var fileNameFromResourceName = _GetFileNameFromResourceName(resourceName);
            if (!fileNameFromResourceName.EndsWith(endingFileName))
            {
                continue;
            }

            using (var manifestResourceStream = assembly.GetManifestResourceStream(resourceName))
            {
                if (manifestResourceStream == null)
                {
                    continue;
                }

                using (var streamReader = new StreamReader(manifestResourceStream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }

        return null;
    }
    
    // https://stackoverflow.com/a/32176198/3764804
    private static string _GetFileNameFromResourceName(string resourceName)
    {
        var stringBuilder = new StringBuilder();
        var escapeDot = false;
        var haveExtension = false;

        for (var resourceNameIndex = resourceName.Length - 1;
            resourceNameIndex >= 0;
            resourceNameIndex--)
        {
            if (resourceName[resourceNameIndex] == '_')
            {
                escapeDot = true;
                continue;
            }

            if (resourceName[resourceNameIndex] == '.')
            {
                if (!escapeDot)
                {
                    if (haveExtension)
                    {
                        stringBuilder.Append('\\');
                        continue;
                    }

                    haveExtension = true;
                }
            }
            else
            {
                escapeDot = false;
            }

            stringBuilder.Append(resourceName[resourceNameIndex]);
        }

        var fileName = Path.GetDirectoryName(stringBuilder.ToString());
        return fileName == null ? null : new string(fileName.Reverse().ToArray());
    }
}

This is a class which you might find very convenient for reading embedded resource files from the current Assembly:

using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;

public static class EmbeddedResourceUtils
{
    public static string ReadFromResourceFile(string endingFileName)
    {
        var assembly = Assembly.GetExecutingAssembly();
        var manifestResourceNames = assembly.GetManifestResourceNames();

        foreach (var resourceName in manifestResourceNames)
        {
            var fileNameFromResourceName = _GetFileNameFromResourceName(resourceName);
            if (!fileNameFromResourceName.EndsWith(endingFileName))
            {
                continue;
            }

            using (var manifestResourceStream = assembly.GetManifestResourceStream(resourceName))
            {
                if (manifestResourceStream == null)
                {
                    continue;
                }

                using (var streamReader = new StreamReader(manifestResourceStream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }

        return null;
    }
    
    // https://stackoverflow.com/a/32176198/3764804
    private static string _GetFileNameFromResourceName(string resourceName)
    {
        var stringBuilder = new StringBuilder();
        var escapeDot = false;
        var haveExtension = false;

        for (var resourceNameIndex = resourceName.Length - 1;
            resourceNameIndex >= 0;
            resourceNameIndex--)
        {
            if (resourceName[resourceNameIndex] == '_')
            {
                escapeDot = true;
                continue;
            }

            if (resourceName[resourceNameIndex] == '.')
            {
                if (!escapeDot)
                {
                    if (haveExtension)
                    {
                        stringBuilder.Append('\\');
                        continue;
                    }

                    haveExtension = true;
                }
            }
            else
            {
                escapeDot = false;
            }

            stringBuilder.Append(resourceName[resourceNameIndex]);
        }

        var fileName = Path.GetDirectoryName(stringBuilder.ToString());
        return fileName == null ? null : new string(fileName.Reverse().ToArray());
    }
}
您的好友蓝忘机已上羡 2024-09-18 05:11:56

答案很简单,如果您直接从 resources.resx 添加文件,只需执行此操作即可。

string textInResourceFile = fileNameSpace.Properties.Resources.fileName;

通过该行代码,可以直接从文件中读取文件中的文本并将其放入字符串变量中。

The answer is quite simple, simply do this if you added the file directly from the resources.resx.

string textInResourceFile = fileNameSpace.Properties.Resources.fileName;

With that line of code, the text from the file is directly read from the file and put into the string variable.

ゝ杯具 2024-09-18 05:11:56

正如 SonarCloud 所指出的,更好的做法是:

public class Example
{
    public static void Main()
    { 
        // Compliant: type of the current class
        Assembly assembly = typeof(Example).Assembly; 
        Console.WriteLine("Assembly name: {0}", assem.FullName);

        // Non-compliant
        Assembly assembly = Assembly.GetExecutingAssembly();
        Console.WriteLine("Assembly name: {0}", assem.FullName);
    }
}

As indicated by SonarCloud better to do:

public class Example
{
    public static void Main()
    { 
        // Compliant: type of the current class
        Assembly assembly = typeof(Example).Assembly; 
        Console.WriteLine("Assembly name: {0}", assem.FullName);

        // Non-compliant
        Assembly assembly = Assembly.GetExecutingAssembly();
        Console.WriteLine("Assembly name: {0}", assem.FullName);
    }
}
梦晓ヶ微光ヅ倾城 2024-09-18 05:11:56

我想将嵌入式资源作为字节数组来读取(不假设任何特定编码),最终我使用了 MemoryStream,这使得它非常简单:

using var resStream = assembly.GetManifestResourceStream(GetType(), "file.txt");
var ms = new MemoryStream();
await resStream .CopyToAsync(ms);
var bytes = ms.ToArray();

I wanted to read the embedded resource just as a byte array (without assuming any specific encoding), and I ended up using a MemoryStream which makes it very simple:

using var resStream = assembly.GetManifestResourceStream(GetType(), "file.txt");
var ms = new MemoryStream();
await resStream .CopyToAsync(ms);
var bytes = ms.ToArray();
请爱~陌生人 2024-09-18 05:11:56
public class AssemblyTextFileReader
{
    private readonly Assembly _assembly;

    public AssemblyTextFileReader(Assembly assembly)
    {
        _assembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
    }

    public async Task<string> ReadFileAsync(string fileName)
    {
        var resourceName = _assembly.GetManifestResourceName(fileName);

        using (var stream = _assembly.GetManifestResourceStream(resourceName))
        {
            using (var reader = new StreamReader(stream))
            {
                return await reader.ReadToEndAsync();
            }
        }
    }
}

public static class AssemblyExtensions
{
    public static string GetManifestResourceName(this Assembly assembly, string fileName)
    {
        string name = assembly.GetManifestResourceNames().SingleOrDefault(n => n.EndsWith(fileName, StringComparison.InvariantCultureIgnoreCase));

        if (string.IsNullOrEmpty(name))
        {
            throw new FileNotFoundException(
quot;Embedded file '{fileName}' could not be found in assembly '{assembly.FullName}'.", fileName);
        }

        return name;
    }
}
// To use the code above:
var reader = new AssemblyTextFileReader(assembly);

string text = await reader.ReadFileAsync(@"MyFile.txt");
public class AssemblyTextFileReader
{
    private readonly Assembly _assembly;

    public AssemblyTextFileReader(Assembly assembly)
    {
        _assembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
    }

    public async Task<string> ReadFileAsync(string fileName)
    {
        var resourceName = _assembly.GetManifestResourceName(fileName);

        using (var stream = _assembly.GetManifestResourceStream(resourceName))
        {
            using (var reader = new StreamReader(stream))
            {
                return await reader.ReadToEndAsync();
            }
        }
    }
}

public static class AssemblyExtensions
{
    public static string GetManifestResourceName(this Assembly assembly, string fileName)
    {
        string name = assembly.GetManifestResourceNames().SingleOrDefault(n => n.EndsWith(fileName, StringComparison.InvariantCultureIgnoreCase));

        if (string.IsNullOrEmpty(name))
        {
            throw new FileNotFoundException(
quot;Embedded file '{fileName}' could not be found in assembly '{assembly.FullName}'.", fileName);
        }

        return name;
    }
}
// To use the code above:
var reader = new AssemblyTextFileReader(assembly);

string text = await reader.ReadFileAsync(@"MyFile.txt");
抱着落日 2024-09-18 05:11:56

我很恼火的是,您必须始终在字符串中包含名称空间和文件夹。我想简化对嵌入式资源的访问。这就是我写这个小课程的原因。欢迎使用和改进!

用途:

using(Stream stream = EmbeddedResources.ExecutingResources.GetStream("filename.txt"))
{
 //...
}

类别:

public class EmbeddedResources
{
    private static readonly Lazy<EmbeddedResources> _callingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetCallingAssembly()));

    private static readonly Lazy<EmbeddedResources> _entryResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetEntryAssembly()));

    private static readonly Lazy<EmbeddedResources> _executingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetExecutingAssembly()));

    private readonly Assembly _assembly;

    private readonly string[] _resources;

    public EmbeddedResources(Assembly assembly)
    {
        _assembly = assembly;
        _resources = assembly.GetManifestResourceNames();
    }

    public static EmbeddedResources CallingResources => _callingResources.Value;

    public static EmbeddedResources EntryResources => _entryResources.Value;

    public static EmbeddedResources ExecutingResources => _executingResources.Value;

    public Stream GetStream(string resName) => _assembly.GetManifestResourceStream(_resources.Single(s => s.Contains(resName)));

}

I was annoyed that you had to always include the namespace and the folder in the string. I wanted to simplify the access to the embedded resources. This is why I wrote this little class. Feel free to use and improve!

Usage:

using(Stream stream = EmbeddedResources.ExecutingResources.GetStream("filename.txt"))
{
 //...
}

Class:

public class EmbeddedResources
{
    private static readonly Lazy<EmbeddedResources> _callingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetCallingAssembly()));

    private static readonly Lazy<EmbeddedResources> _entryResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetEntryAssembly()));

    private static readonly Lazy<EmbeddedResources> _executingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetExecutingAssembly()));

    private readonly Assembly _assembly;

    private readonly string[] _resources;

    public EmbeddedResources(Assembly assembly)
    {
        _assembly = assembly;
        _resources = assembly.GetManifestResourceNames();
    }

    public static EmbeddedResources CallingResources => _callingResources.Value;

    public static EmbeddedResources EntryResources => _entryResources.Value;

    public static EmbeddedResources ExecutingResources => _executingResources.Value;

    public Stream GetStream(string resName) => _assembly.GetManifestResourceStream(_resources.Single(s => s.Contains(resName)));

}
巾帼英雄 2024-09-18 05:11:56

对于所有只想快速获取 winforms 中硬编码文件文本的人;

  1. 在解决方案资源管理器中右键单击您的应用程序>资源>添加您的文件。
  2. 单击它,然后在属性选项卡中将“文件类型”设置为“文本”。
  3. 在您的程序中,只需执行 Resources..toString(); 即可读取文件。

我不会推荐将此作为最佳实践或任何其他内容,但它运行速度很快并且可以完成所需的工作。

For all the people that just quickly want the text of a hardcoded file in winforms;

  1. Right-click your application in the solution explorer > Resources > Add your file.
  2. Click on it, and in the properties tab set the "FileType" to "Text".
  3. In your program just do Resources.<name of resource>.toString(); to read the file.

I would not recommend this as best practice or anything, but it works quickly and does what it needs to do.

忘年祭陌 2024-09-18 05:11:56

这里的大多数答案将基本或完整名称空间作为常量,或迭代 GetManifestResourceNames 中的所有资源来获取它。
我有更简单但不完美的解决方案:

var ns = typeof(Form1).Namespace;
var filename = "MyFile.txt";
using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream($"{ns}.{filename}"))
using (var sr = new StreamReader(s))
{
    var text = sr.ReadToEnd();
}

// OR
var ns = this.GetType().Namespace;
var filename = "MyFile.txt";
using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream($"{ns}.{filename}"))
using (var sr = new StreamReader(s))
{
    var text = sr.ReadToEnd();
}

当然文件应标记为“嵌入式资源”。

Most of answers here holds base or full namespace as a constant or iterate over all resources from GetManifestResourceNames to get it.
I have much simpler but not perfect solution:

var ns = typeof(Form1).Namespace;
var filename = "MyFile.txt";
using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream(
quot;{ns}.{filename}"))
using (var sr = new StreamReader(s))
{
    var text = sr.ReadToEnd();
}

// OR
var ns = this.GetType().Namespace;
var filename = "MyFile.txt";
using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream(
quot;{ns}.{filename}"))
using (var sr = new StreamReader(s))
{
    var text = sr.ReadToEnd();
}

Of course file shold be marked as "Embedded Resource".

温暖的光 2024-09-18 05:11:56

读取表单加载事件中的嵌入式 TXT 文件。

动态设置变量。

string f1 = "AppName.File1.Ext";
string f2 = "AppName.File2.Ext";
string f3 = "AppName.File3.Ext";

调用 Try Catch。

try 
{
     IncludeText(f1,f2,f3); 
     /// Pass the Resources Dynamically 
     /// through the call stack.
}

catch (Exception Ex)
{
     MessageBox.Show(Ex.Message);  
     /// Error for if the Stream is Null.
}

为 IncludeText() 创建 Void,Visual Studio 会为您执行此操作。单击灯泡以自动生成代码块。

将以下内容放入生成的代码块

资源 1

var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(file1))
using (StreamReader reader = new StreamReader(stream))
{
string result1 = reader.ReadToEnd();
richTextBox1.AppendText(result1 + Environment.NewLine + Environment.NewLine );
}

资源 2

var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(file2))
using (StreamReader reader = new StreamReader(stream))
{
string result2 = reader.ReadToEnd();
richTextBox1.AppendText(
result2 + Environment.NewLine + 
Environment.NewLine );
}

资源 3

var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(file3))

using (StreamReader reader = new StreamReader(stream))
{
    string result3 = reader.ReadToEnd();
    richTextBox1.AppendText(result3);
}

如果您希望将返回的变量发送到其他地方,只需调用另一个函数,然后...

using (StreamReader reader = new StreamReader(stream))
{
    string result3 = reader.ReadToEnd();
    ///richTextBox1.AppendText(result3);
    string extVar = result3;

    /// another try catch here.

   try {

   SendVariableToLocation(extVar)
   {
         //// Put Code Here.
   }

       }

  catch (Exception ex)
  {
    Messagebox.Show(ex.Message);
  }

}

这实现的是一个组合方法多个 txt 文件,并在单个富文本框中读取其嵌入数据。这是我对这个代码示例所期望的效果。

Read Embedded TXT FILE on Form Load Event.

Set the Variables Dynamically.

string f1 = "AppName.File1.Ext";
string f2 = "AppName.File2.Ext";
string f3 = "AppName.File3.Ext";

Call a Try Catch.

try 
{
     IncludeText(f1,f2,f3); 
     /// Pass the Resources Dynamically 
     /// through the call stack.
}

catch (Exception Ex)
{
     MessageBox.Show(Ex.Message);  
     /// Error for if the Stream is Null.
}

Create Void for IncludeText(), Visual Studio Does this for you. Click the Lightbulb to AutoGenerate The CodeBlock.

Put the following inside the Generated Code Block

Resource 1

var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(file1))
using (StreamReader reader = new StreamReader(stream))
{
string result1 = reader.ReadToEnd();
richTextBox1.AppendText(result1 + Environment.NewLine + Environment.NewLine );
}

Resource 2

var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(file2))
using (StreamReader reader = new StreamReader(stream))
{
string result2 = reader.ReadToEnd();
richTextBox1.AppendText(
result2 + Environment.NewLine + 
Environment.NewLine );
}

Resource 3

var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(file3))

using (StreamReader reader = new StreamReader(stream))
{
    string result3 = reader.ReadToEnd();
    richTextBox1.AppendText(result3);
}

If you wish to send the returned variable somewhere else, just call another function and...

using (StreamReader reader = new StreamReader(stream))
{
    string result3 = reader.ReadToEnd();
    ///richTextBox1.AppendText(result3);
    string extVar = result3;

    /// another try catch here.

   try {

   SendVariableToLocation(extVar)
   {
         //// Put Code Here.
   }

       }

  catch (Exception ex)
  {
    Messagebox.Show(ex.Message);
  }

}

What this achieved was this, a method to combine multiple txt files, and read their embedded data, inside a single rich text box. which was my desired effect with this sample of Code.

鸩远一方 2024-09-18 05:11:56

对于使用 VB.Net 的用户,

Imports System.IO
Imports System.Reflection

Dim reader As StreamReader
Dim ass As Assembly = Assembly.GetExecutingAssembly()
Dim sFileName = "MyApplicationName.JavaScript.js" 
Dim reader = New StreamReader(ass.GetManifestResourceStream(sFileName))
Dim sScriptText = reader.ReadToEnd()
reader.Close()

其中 MyApplicationName 是我的应用程序的命名空间。
它不是程序集名称。
该名称在项目属性(“应用程序”选项卡)中定义。

如果找不到正确的资源名称,可以使用 GetManifestResourceNames()

Dim resourceName() As String = ass.GetManifestResourceNames()

Dim sName As String 
    = ass.GetManifestResourceNames()
        .Single(Function(x) x.EndsWith("JavaScript.js"))

函数

Dim sNameList 
    = ass.GetManifestResourceNames()
        .Where(Function(x As String) x.EndsWith(".js"))

For users that are using VB.Net

Imports System.IO
Imports System.Reflection

Dim reader As StreamReader
Dim ass As Assembly = Assembly.GetExecutingAssembly()
Dim sFileName = "MyApplicationName.JavaScript.js" 
Dim reader = New StreamReader(ass.GetManifestResourceStream(sFileName))
Dim sScriptText = reader.ReadToEnd()
reader.Close()

where MyApplicationName is namespace of my application.
It is not the assembly name.
This name is define in project's properties (Application tab).

If you don't find correct resource name, you can use GetManifestResourceNames() function

Dim resourceName() As String = ass.GetManifestResourceNames()

or

Dim sName As String 
    = ass.GetManifestResourceNames()
        .Single(Function(x) x.EndsWith("JavaScript.js"))

or

Dim sNameList 
    = ass.GetManifestResourceNames()
        .Where(Function(x As String) x.EndsWith(".js"))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文