how to convert stream data to string

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am getting data from an FTP into a Stream object. Now I need to put this
data into a string so I can manipulate it. Can anyone show me some example
code?
 
That depends on what your 'data' is. You'll probably want to move it from
the stream into a byte[] and pass it to System.Text.Encoding.* (like ASCII,
etc - depends on what your data is).
 
The data is text from a text file from a FTP location... you wouldn't happen
to have a code example would you?

Adam Clauss said:
That depends on what your 'data' is. You'll probably want to move it from
the stream into a byte[] and pass it to System.Text.Encoding.* (like ASCII,
etc - depends on what your data is).

--
Adam Clauss


tparks69 said:
I am getting data from an FTP into a Stream object. Now I need to put this
data into a string so I can manipulate it. Can anyone show me some
example
code?
 
Hi,

You can feed the Stream to a StreamReader and use ReadToEnd to the data as
String (note the default encoding of UTF8, any other encoding needs to be
specified in the StreamReader constructor).

string data = "";
using (StreamReader sr = new StreamReader(Stream,
Encoding.GetEncoding("ISO-8859-1")))
{
data = sr.ReadToEnd();
}

As the file is transferred over a network you may instead want to use a
MemoryStream as temporary storage while reading the network stream, and at
the end use MemoryStream.ToArray() to get the byte[]. The byte array can
be transferred to string using the Encoding class.
Encoding.UTF8.GetString(byte[])

string data = "";
int bytesRead = 0;
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[8096];
while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
// optional feedback on progress
}
data = Encoding.UTF8.GetString(ms.ToArray());
}

The former sample is easy, but will hang during the transfer until the
entire stream is read. The latter sample is more complex, but has the
advantage of being able to give feedback on the progress of the file
transfer.


The data is text from a text file from a FTP location... you wouldn't
happen
to have a code example would you?

Adam Clauss said:
That depends on what your 'data' is. You'll probably want to move it
from
the stream into a byte[] and pass it to System.Text.Encoding.* (like
ASCII,
etc - depends on what your data is).

--
Adam Clauss


tparks69 said:
I am getting data from an FTP into a Stream object. Now I need to put this
data into a string so I can manipulate it. Can anyone show me some
example
code?
 
Back
Top