2011-04-08 155 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; 
    } 
} 
相關問題