2011-04-08 152 views
2

这并不工作:使用StreamReader打开资源文件?

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

如何打开一个资源文件,以获取其内容是什么?

+2

什么是“不工作”意思?它是否会抛出异常?它是否默默地失败? – 2011-04-08 18:14:27

+2

请参阅:http://stackoverflow.com/questions/5342975/get-a-textreader-from-a-stream/5343005#5343005 – 2011-04-08 18:14:53

+0

资源文件通常是一个二进制文件。用StreamReader读取它可能不会给你想要的信息。请参阅@Arnaud F.提供的用于从流中读取文本资源的答案。 – 2011-04-08 18:23:02

回答

5

尝试这样的:

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]; 
    } 
} 
+0

我有一个名为security.file的文件。这是一个文本文件,当我将Resource.text分配给fileContent时。它是一个字节[],不能隐式转换为字符串 – 2013-07-26 14:34:57

0

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

0

阅读资源,你需要一个名为“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; 
    } 
} 
相关问题