从数据流中获取文本阅读器?

我试图读取一个嵌入式文本文件与 System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);,但它给我一个 Stream。嵌入的资源是一个文本文件,因此,我怎样才能把这个 Stream变成一个 TextReader

74165 次浏览

A StreamReader is a subclass of TextReader, so you will be able to do:

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

You can read your resource file like this :

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;
}
}
TextReader tr = new StreamReader(stream);

You need to get a StreamReader from it (TextReader is an abstract base class of StreamReader and StringReader). Something like:

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