Share via

Read FileStream

Peter Volz 1,295 Reputation points
2023-06-16T18:08:26.14+00:00

Hello all

I have a function which has an input Stream, if it's MemoryStream, I can get its text content by:

Encoding.ASCII.GetString(InputStream.ToArray)

But, if it is FileStream, how to get the whole file contents as text string?

This is what I found but why write it to byte()?

InputStream.Read(Byte(), 0, Convert.ToInt32(InputStream.Length))

Any short efficient way to go? :)

Developer technologies | VB
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


1 answer

Sort by: Most helpful
  1. P a u l 10,766 Reputation points
    2023-06-16T18:24:00.5933333+00:00

    You can just use StreamReader and specify the encoding you of the data (ASCII here as per your example):

    await PrintStream(new MemoryStream(Encoding.ASCII.GetBytes("Hello world!")));
    await PrintStream(new FileStream("./test.txt", FileMode.Open));
    
    await Console.Out.WriteLineAsync();
    
    async Task PrintStream(Stream stream) {
    	var reader = new StreamReader(stream, Encoding.ASCII);
    
    	Console.WriteLine(await reader.ReadToEndAsync());
    }
    

    Disclaimer: If the data isn't too big this method is fine, but if you're dealing with huge files (like a binary image file) then you should prefer the Read option so you can read the data in chunks to avoid dragging too much into memory at one time.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.