从流中获取TextReader?


81

我正在尝试使用读取嵌入式文本文件,System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);但它给了我一个Stream。嵌入式资源是一个文本文件,因此如何将其Stream转换为TextReader

Answers:



18

AStreamReader是的子类TextReader,因此您可以执行以下操作:

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

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

一个foreach环比的显式枚举更好。
R. Martinho Fernandes

5

您需要从中获取一个StreamReader(TextReader是StreamReader和StringReader的抽象基类)。就像是:

var stream = System.Reflection.Assembly.GetExecutingAssembly().
    GetManifestResourceStream(resource);
var reader = new StreamReader(stream);
var text = reader.ReadToEnd();
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.