Need Help with Writing a IO.Stream
-
I am writing a webservice that allows a user to upload files. i had no problem handling pictures but i am having trouble handling plain text files. How do I write out my stream to a text file that the webservice receives from the client? HOw do I take my System.IO.Stream and pass it into a FileStream so that I can write the file anywhere I want on the server? Thanks in advance
-
I am writing a webservice that allows a user to upload files. i had no problem handling pictures but i am having trouble handling plain text files. How do I write out my stream to a text file that the webservice receives from the client? HOw do I take my System.IO.Stream and pass it into a FileStream so that I can write the file anywhere I want on the server? Thanks in advance
Pass the
Stream
into the constructor of aStreamReader
, then buffer the input (in blocks, for which 4096 is a good size typically) to aTextWriter
derivative (perhaps aStreamWriter
with aFileStream
passed to its constructor that points at the right place. This will also allow you to change the encoding if you like. You could skip the readers and writers, though, and just buffer the input directly from theStream
to aFileStream
, something like:private void Save(Stream s)
{
FileStream file = new FileStream("c:\temp\file.txt", ...);
using (file)
{
byte[] buffer = new byte[4096];
int read = 0;
read = s.Read(buffer, 0, buffer.Length);
while (read != 0)
{
file.Write(buffer, 0, read);
read = s.Read(buffer, 0, buffer.Length);
}
}
}A very simplistic example, but you should get the idea. The code would be similar using a
TextReader
andTextWriter
derivative, but would allow you to more easily handle text as opposed to binary data (although you could still get an encoded string at any time using theEncoding
class derivatives).Microsoft MVP, Visual C# My Articles