Get a TextReader from a Stream?

后端 未结 4 1576
北恋
北恋 2021-02-04 23:21

I\'m trying to read an embedded text file with System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resource); but it gives me a Stream

相关标签:
4条回答
  • 2021-02-04 23:32

    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.
    }
    
    0 讨论(0)
  • 2021-02-04 23:44

    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();
    
    0 讨论(0)
  • 2021-02-04 23:46
    TextReader tr = new StreamReader(stream);
    
    0 讨论(0)
  • 2021-02-04 23:46

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题