Create an object of type Stream from a string

2

I need to create an object of type System.IO.Stream from the contents of a string . This my string is in a Resource.resx file. I retrieve it like this:

string xml = ResourcesRel.pt_BR;

I need to use a component that has a Load() method. This method has two overloads: one that accepts the physical path of the file, and another that accepts Stream .

Can you create a Stream object from the string ?

    
asked by anonymous 22.02.2017 / 20:00

2 answers

5

You can convert to bytes and then to MemoryStream which is an object that inherits from System.IO.Stream .

string conteudo = "Teste";
byte[] array = Encoding.UTF8.GetBytes(conteudo);
MemoryStream stream = new MemoryStream(array);
    
22.02.2017 / 20:08
4

You can use MemoryStream . You have to see if you need to do some conversion before or not.

using System.IO;
using System;

public class Program {
    public static void Main() {
        var texto = "meu texto aqui";
        var stream = new MemoryStream();
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(texto);
        writer.Flush();
        stream.Position = 0;
        var reader = new StreamReader(stream); //aqui já está consumindo o stream
        var novotexto = reader.ReadToEnd();
        Console.WriteLine(novotexto); //só pra mostrar funcionando
    }
}

See running on .NET Fiddle . And at Coding Ground . Also put it on GitHub for future reference .

If you prefer you can do this:

var stream = new MemoryStream(Encoding.UTF8.GetBytes("meu texto aqui"));
    
22.02.2017 / 20:10