从流中获取TextReader?

时间:2011-03-17 17:40:27

标签: c# .net io

我正在尝试使用System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);阅读嵌入的文本文件,但它为我提供了Stream。嵌入资源是一个文本文件,那么如何将此Stream变为TextReader

4 个答案:

答案 0 :(得分:167)

TextReader tr = new StreamReader(stream);

答案 1 :(得分:18)

StreamReaderTextReader的子类,因此您可以这样做:

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

答案 2 :(得分:5)

您可以像这样阅读资源文件:

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

答案 3 :(得分:5)

您需要从中获取StreamReader(TextReader是StreamReader和StringReader的抽象基类)。类似的东西:

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