IT-Swarm.Net

从流中获取TextReader?

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

70
Juan
TextReader tr = new StreamReader(stream);
167
Teo Klestrup Röijezon

快速,可靠且价格合理的云托管

注册并在30天内获得$50奖金!

StreamReaderTextReader的子类,所以你可以这样做:

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

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

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;
    }
}
4
Arnaud F.

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

var stream = System.Reflection.Assembly.GetExecutingAssembly().
    GetManifestResourceStream(resource);
var reader = new StreamReader(stream);
var text = reader.ReadToEnd();
4
Paul Kearney - pk