2011-03-17 75 views
54

我正在嘗試使用System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);來讀取嵌入的文本文件,但它給了我一個Stream。嵌入式資源是一個文本文件,所以我怎樣才能把這個Stream變成TextReader從流中獲取TextReader?

回答

141
TextReader tr = new StreamReader(stream); 
17

一個StreamReaderTextReader一個子類,所以你可以做:

using(var stream = System.Reflection.Assembly.GetExecutingAssembly(). 
    GetManifestResourceStream(resource)) 
using(var reader = new StreamReader(stream)) 
{ 
    // Use reader. 
} 
4

你可以這樣寫的資源文件:

Assembly resourceAssembly = Assembly.LoadFrom(resourceFile.FullName); 
string[] manifests = resourceAssembly.GetManifestResourceNames(); 

using (ResourceReader reader = new ResourceReader(
    resourceAssembly.GetManifestResourceStream(manifests[0]))) 
{ 
    foreach (IDictionaryEnumerator dict in reader) 
    { 
     string key = dict.Key as string; 
     object val = dict.Value; 
    } 
} 
+0

「foreach」循環比明確的枚舉器更好。 – 2011-03-17 17:48:34

+0

@Martinho:固定,謝謝。 – 2011-03-17 17:57:09

4

你需要得到它的StreamReader(TextReader是StreamReader和StringReader的抽象基類)。例如:

var stream = System.Reflection.Assembly.GetExecutingAssembly(). 
    GetManifestResourceStream(resource); 
var reader = new StreamReader(stream); 
var text = reader.ReadToEnd();