Create a Stream object from a string

Asked

Viewed 757 times

3

I need to create an object of the type System.IO.Stream from the content of a string. This one of mine string is in an archive Resource.resx. I get her back that way:

string xml = ResourcesRel.pt_BR;

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

You can create an object Stream from the string?

  • Basically that would not be http://stackoverflow.com/a/1879470/2221388?

2 answers

9


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

string conteudo = "Teste";
byte[] array = Encoding.UTF8.GetBytes(conteudo);
MemoryStream stream = new MemoryStream(array);
  • I will accept this answer because it was the first, and it is simpler (fewer lines of code). Apparently I had no problem with it.

6

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

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

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

If you prefer you can do this:

var stream = new MemoryStream(Encoding.UTF8.GetBytes("meu texto aqui"));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.