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

问题描述 投票:599回答:17

如何阅读使用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();
}
.net embedded-resource streamreader
17个回答
1090
投票

您可以使用Assembly.GetManifestResourceStream Method

  1. 添加以下使用 qazxsw POI
  2. 相关文件的设置属性: 与价值using System.IO; using System.Reflection; 参数Build Action
  3. 使用下面的代码

Embedded Resource

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的资源之一的名称。例如,如果您嵌入了一个名为assembly文本文件,该文件被放置在默认命名空间"MyFile.txt"一个项目的根目录,然后"MyCompany.MyProduct"resourceName。您可以使用"MyCompany.MyProduct.MyFile.txt"在装配中得到的所有资源的列表。


没有道理的精明让仅从文件名Assembly.GetManifestResourceNames Method(擦肩而过命名空间的东西):

resourceName

6
投票

通过将所有的权力结合我用这个辅助类可以从任何组件,并且在一般的方式任何命名空间的阅读资源。

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

4
投票

我读嵌入的资源文本文件的使用:

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

样品:

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

3
投票

我知道这是老了,但我只是想指出的NETMF(.NET MicroFramework),你可以很容易地做到这一点:

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

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

由于NETMF没有string response = Resources.GetString(Resources.StringResources.MyFileName);


3
投票

看完所有的解决方案张贴在这里。这是我如何解决它:

GetManifestResourceStream

2
投票

我很生气,你必须始终包含命名空间和字符串中的文件夹中。我想简化访问嵌入的资源。这就是为什么我写了这个小类。随意使用和提高!

用法:

// 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 "";      
}

类:

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

2
投票

答案很简单,只要做到这一点,如果你直接从resources.resx添加的文件。

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

}

随着该行代码,从文件中的文本是直接从文件中读取并投入字符串变量。


1
投票
string textInResourceFile = fileNameSpace.Properties.Resources.fileName;

0
投票

阅读Form Load事件嵌入式文本文件。

Set the Variables Dynamically.

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($"Embedded file '{fileName}' could not be found in assembly '{assembly.FullName}'.", fileName);
        }

        return name;
    }
}

Call a Try Catch.

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

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

把生成的代码块内的以下

资源1

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

资源2

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

资源3

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

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

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

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

这是什么实现是这样,组合多个txt文件,并阅读他们的嵌入式数据,一个丰富的文本框内的方法。这与此示例代码的我想要的效果。


125
投票

您可以添加一个文件作为两种不同的方法的资源。

访问该文件所需要的C#代码是不同的,这取决于所使用添加的文件在第一位置的方法。

方法1:添加现有的文件,设置属性为string resourceName = assembly.GetManifestResourceNames() .Single(str => str.EndsWith("YourFileName.txt"));

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

注:如果您使用此方法添加的文件,你可以使用Embedded Resource访问它(见GetManifestResourceStream)。

方法2:添加文件answer from @dtb

开拓Resources.resx文件,使用下拉框添加的文件,设置Resources.resxAccess Modifier

注:如果您使用此方法添加的文件,你可以使用public访问它(见Properties.Resources)。


84
投票

基本上,你用answer from @Night Walker去本届大会的参考。然后,使用System.Reflection

例如,我贴的页面:

注:需要为它添加GetManifestResourceStream()工作

using System.Reflection;

68
投票

在Visual Studio中,你可以直接通过项目属性(在这个例子中“分析”)的资源选项卡中嵌入访问文件资源。

将得到的文件可以由一个字节数组访问

   Assembly _assembly;
   StreamReader _textStreamReader;

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

如果你需要它作为一个流,然后(从byte[] jsonSecrets = GoogleAnalyticsExtractor.Properties.Resources.client_secrets_reporter;

https://stackoverflow.com/a/4736185/432976

27
投票

当您添加文件到资源,就应该选择它的访问修饰符为public比你可以像下面。

Stream stream = new MemoryStream(jsonSecrets)

CLIST01是嵌入式文件的名称。

其实你可以去resources.Designer.cs,看看什么是吸气的名称。


12
投票

我知道这是一个古老的线程,但是这是对我工作:

  1. 该文本文件添加到项目资源
  2. 访问修饰符设置为公开,如上由安德鲁·希尔表现
  3. 读这样的文字: byte[] clistAsByteArray = Properties.Resources.CLIST01;

我加入到资源的文字:“SomeText.txt”


12
投票

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

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

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


8
投票

您还可以使用@ DTB的回答这个简化版:

enter image description here

7
投票

事情现在我只是学到的是,你的文件是不允许有“” (点)中的文件名。

Templates.plainEmailBodyTemplate-en.txt - >作品! Templates.plainEmailBodyTemplate.en.txt - >通过GetManifestResourceStream不工作()

大概是因为框架会很困惑,在命名空间VS名...

© www.soinside.com 2019 - 2024. All rights reserved.