【问题标题】:Open a resource file with StreamReader?使用 StreamReader 打开资源文件?
【发布时间】:2011-04-08 18:12:45
【问题描述】:

这不起作用:

string fileContent = Resource.text;
    StreamReader read = File.OpenText(fileContent);

    string line;
            char[] splitChar = "|".ToCharArray();

            while ((line = read.ReadLine()) != null)
            {
                string[] split = line.Split(splitChar);
                string name = split[0];
                string lastname = split[1];

            }

            read.Dispose();

如何打开资源文件以获取其内容?

【问题讨论】:

  • “不起作用”是什么意思?它会抛出异常吗?它会默默地失败吗?
  • 资源文件通常是二进制文件。用StreamReader 阅读它可能不会给你想要的信息。请参阅@Arnaud F. 提供的从流中读取文本资源的答案。

标签: c#


【解决方案1】:

试试这样:

string fileContent = Resource.text;
using (var reader = new StringReader(fileContent))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        string[] split = line.Split('|');
        string name = split[0];
        string lastname = split[1];
    }
}

【讨论】:

  • 我有一个名为 security.file 的文件。它是一个文本文件,当我将 Resource.text 分配给 fileContent 时。它是一个字节[],不能隐式转换为字符串
【解决方案2】:

我认为变量 fileContent 已经包含了你需要的所有内容。

【讨论】:

    【解决方案3】:

    要读取资源,你需要一个名为“ResourceReader”的特殊流,你可以这样使用它:

    string fileContent = "<your resource file>";
    
    using (ResourceReader reader = new ResourceReader(fileContent))
    {
        foreach (IDictionaryEnumerator dict in reader)
        {
            string key = dict.Key as string;
            object val = dict.Value;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-28
      • 1970-01-01
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      相关资源
      最近更新 更多