C# FileStream - read & write files in C# with FileStream (2024)

last modified July 5, 2023

C# FileStream tutorial shows how to read & write files in C# with FileStream.

C# FileStream

FileStream provides a Stream for a file, supportingboth synchronous and asynchronous read and write operations. A stream is a flowof data from a source into a destination. The source or destination can be adisk, memory, socket, or other programs.

When we use FileStream, we work with bytes. For more convenientwork with text data, we can use StreamWriter andStreamReader.

C# FileStream write text

In the following example, we write text data into a file withFileStream.

Program.cs

using System.Text;var fileName = @"C:\Users\Jano\Documents\words.txt";using FileStream fs = File.OpenWrite(fileName);var data = "falcon\nhawk\nforest\ncloud\nsky";byte[] bytes = Encoding.UTF8.GetBytes(data);fs.Write(bytes, 0, bytes.Length);

The example writes a couple of words into a text file.

using FileStream fs = File.OpenWrite(fileName);

The File.OpenWrite method opens a FileStream in awriting mode.

var data = "falcon\nhawk\nforest\ncloud\nsky";byte[] bytes = Encoding.UTF8.GetBytes(data);

We have text data which we transform into bytes withEncoding.UTF8.GetBytes.

fs.Write(bytes, 0, bytes.Length);

The bytes are written to the FileStream with Write.

C# FileStream write text with StreamWriter

In the following example, we use FileStream in combination withStreamWriter.

Program.cs

var fileName = @"C:\Users\Jano\Documents\words.txt";using FileStream fs = File.Create(fileName);using var sr = new StreamWriter(fs);sr.WriteLine("coin\nfalcon\nhawk\nforest");Console.WriteLine("done");

The example writes text data into a file. For convenience, we use theStreamWriter, which writes characters to a stream in a particularencoding.

using FileStream fs = File.Create(fileName);using var sr = new StreamWriter(fs);

A StreamWriter is created; it takes the FileStreamas a parameter.

sr.WriteLine("coin\nfalcon\nhawk\nforest");

A line of text is written to the FileStream withWriteLine.

C# FileStream read text

In the following example, we read data from a text file with FileStream.

Program.cs

using System.Text;var fileName = @"C:\Users\Jano\Documents\words.txt";using FileStream fs = File.OpenRead(fileName);byte[] buf = new byte[1024];int c;while ((c = fs.Read(buf, 0, buf.Length)) > 0){ Console.WriteLine(Encoding.UTF8.GetString(buf, 0, c));}

The example reads a text file and prints its contents. We read the data asbytes, transform them into strings using UTF8 encoding and finally, write thestrings to the console.

using FileStream fs = File.OpenRead(fileName);

With File.OpenRead we open a file for reading. The method returnsa FileStream.

byte[] buf = new byte[1024];

The buf is a byte array into which we read the datafrom the file.

while ((c = fs.Read(buf, 0, buf.Length)) > 0){ Console.WriteLine(Encoding.UTF8.GetString(buf, 0, c));}

The FileStream's Read method reads a block of bytesfrom the stream and writes the data in a given buffer. The first argument is thebyte offset in array at which the read bytes will be placed. The second is themaximum number of bytes to read. The Encoding.UTF8.GetStringdecodes all the bytes in the specified byte array into a string.

C# FileStream read text with StreamReader

In the following example, we use FileStream in combination withStreamReader.

Program.cs

var fileName = @"C:\Users\Jano\Documents\words.txt";using FileStream fs = File.OpenRead(fileName);using var sr = new StreamReader(fs);string line;while ((line = sr.ReadLine()) != null){ Console.WriteLine(line);}

In the example, we read a text file. When we use StreamReader, wedo not need to do the decoding of bytes into characters.

using FileStream fs = File.OpenRead(fileName);using var sr = new StreamReader(fs);

We pass the FileStream to the StreamReader. If we donot explicitly specify the encoding, the default UTF8 is used.

string line;while ((line = sr.ReadLine()) != null){ Console.WriteLine(line);}

We read the data with the StreamReader's WriteLinemethod. It returns the next line from the input stream, or null ifthe end of the input stream is reached.

C# FileStream CopyTo

The CopyTo method reads the bytes from the current stream andwrites them to another stream.

Program.cs

var fileName = "words.txt";using var fs = new FileStream(fileName, FileMode.Open);var fileName2 = "words_copy.txt";using var fs2 = new FileStream(fileName2, FileMode.OpenOrCreate);fs.CopyTo(fs2);Console.WriteLine("File copied");

The examples copies a text file with CopyTo method.

C# FileStream download image

In the following example, we download a small image file.

Program.cs

using var httpClient = new HttpClient();var url = "http://webcode.me/favicon.ico";byte[] imageBytes = await httpClient.GetByteArrayAsync(url);using var fs = new FileStream("favicon.ico", FileMode.Create);fs.Write(imageBytes, 0, imageBytes.Length);Console.WriteLine("Image downloaded");

The example uses the HttpClient to download a small image file.The image is retrieved as an array of bytes. The bytes are then written toa FileStream.

using var fs = new FileStream("favicon.ico", FileMode.Create);fs.Write(imageBytes, 0, imageBytes.Length);

We create a new file for writing. The bytes are written to the newly createdfile with the Write method.

C# FileStream read image

In the next example, we read an image file. We output the file as hexadecimaldata.

Program.cs

var fileName = @"C:\Users\Jano\Documents\favicon.ico";using var fs = new FileStream(fileName, FileMode.Open);int c;int i = 0;while ((c = fs.ReadByte()) != -1){ Console.Write("{0:X2} ", c); i++; if (i % 10 == 0) { Console.WriteLine(); }}

The example outputs a small image in hexadecimal notation.

while ((c = fs.ReadByte()) != -1){

The ReadByte method reads a byte from the file and advancesthe read position one byte. It returns the byte, cast to an Int32,or -1 if the end of the stream has been reached. It is OK toread the image by one byte since we deal with a very small image.

Console.Write("{0:X2} ", c);

The {0:X2} outputs the bytes in hexadecimal notation.

if (i % 10 == 0){ Console.WriteLine();}

We write a new line character after ten columns.

C# FileStream streaming

Streaming is a method of transmitting of data in a continuous stream that can beprocessed by the receiving computer before the entire file has been completelysent.

Program.cs

using var httpClient = new HttpClient();var url = "https://cdn.netbsd.org/pub/NetBSD/NetBSD-9.2/images/NetBSD-9.2-amd64-install.img.gz";var fname = Path.GetFileName(url);var resp = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);resp.EnsureSuccessStatusCode();using Stream ms = await resp.Content.ReadAsStreamAsync();using FileStream fs = File.Create(fname);await ms.CopyToAsync(fs);Console.WriteLine("file downloaded");

A NetBSD USB image is downloaded using streaming operation.

using var httpClient = new HttpClient();

HttpClient is used to create HTTP requests.

var resp = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);

With the HttpCompletionOption.ResponseHeadersRead option the asyncoperation should complete as soon as a response is available and headers areread. The content is not read yet. The method will just read the headers andreturns the control back.

using Stream ms = await resp.Content.ReadAsStreamAsync();

The ReadAsStreamAsync methods erialize the HTTP content and returna stream that represents the content as an asynchronous operation.

using FileStream fs = File.Create(fname);

We create a file stream with File.Create; it creates or overwritesa file in the specified path.

await ms.CopyToAsync(fs);

The data is copied continuously to the file stream.

Source

FileStream class - language reference

In this article we have used FileStream to read and write files.

Author

My name is Jan Bodnar and I am a passionate programmer with many years ofprogramming experience. I have been writing programming articles since 2007. Sofar, I have written over 1400 articles and 8 e-books. I have over eight years ofexperience in teaching programming.

List all C# tutorials.

C# FileStream - read & write files in C# with FileStream (2024)
Top Articles
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated:

Views: 5762

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.