Skip to main content

FileStream in C#

 FileStream in C# Explained

FileStream in system.io namespace provides a Stream for a file, supporting both synchronous and asynchronous read and write operations. A stream is a flow of data from a source into a destination. The source or destination can be a disk, memory, socket, or other programs.

When we use FileStream, we work with bytes. For more convenient work with text data, we can use StreamWriter and StreamReader.

Writing text using FileStream in C#

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

using System;

using System.IO;

using System.Text;

 

namespace WriteText

{

    class Program

    {

        static void Main(string[] args)

        {

            var fileName = @"C:\Users\Csharpnaija\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 above writes a couple of words into a text file.

using FileStream fs = File.OpenWrite(fileName);

The File.OpenWrite() method opens a FileStream in a writing mode.


var data = "falcon\nhawk\nforest\ncloud\nsky";

byte[] bytes = Encoding.UTF8.GetBytes(data);

We have text data which we transform into bytes with Encoding.UTF8.GetBytes().

 

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

The bytes are written to the FileStream with Write().

 Writing text using FileStream and StreamWriter in C#

In the following example, we use FileStream in combination with StreamWriter.

using System;

using System.IO;

 

namespace CsharpnaijaTutorial

{

    class Program

    {

        static void Main(string[] args)

        {

            var fileName = @"C:\Users\Csharpnaija\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 above writes text data into a file. For convenience, we use the StreamWriter, which writes characters to a stream in a particular encoding.

 

using FileStream fs = File.Create(fileName);

using var sr = new StreamWriter(fs);

 

As can be seen above, a FileStream is created that takes filename as a parameter and StreamWriter is created; it takes the FileStream as a parameter.

 

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

A line of text is written to the FileStream with WriteLine() method of StreamWriter class.

Reading text using FileStream in C#

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

using System;

using System.IO;

using System.Text;

 

namespace ReadText

{

    class Program

    {

        static void Main(string[] args)

        {

            var fileName = @"C:\Users\Csharpnaija\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 above example reads a text file and prints its contents. We read the data as bytes, transform them into strings using UTF8 encoding and finally, write the strings to the console.

 using FileStream fs = File.OpenRead(fileName);

With File.OpenRead() we open a file for reading. The method returns a FileStream.

byte[] buf = new byte[1024];

The buf is a byte array into which we read the data from 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 bytes from the stream and writes the data in a given buffer. The first argument is the byte offset in array at which the read bytes will be placed. The second is the maximum number of bytes to read. The Encoding.UTF8.GetString() decodes all the bytes in the specified byte array into a string.

Reading text using FileStream with StreamReader in C#

In the following example, we use FileStream in combination with StreamReader.

using System;

using System.IO;

 

namespace csharpnaijaTutorial

{

    class Program

    {

        static void Main(string[] args)

        {

            var fileName = @"C:\Users\csharpnaija\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 above, we read a text file. When we use StreamReader, we do not need to do the decoding of bytes into characters.

using FileStream fs = File.OpenRead(fileName);

using var sr = new StreamReader(fs);

From the above code snippet, we pass the FileStream to the StreamReader. If we do not 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 WriteLine() method. It returns the next line from the input stream, or null if the end of the input stream is reached.

Downloading Image Using FileStream in C#

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

using System;

using System.IO;

using System.Net.Http;

using System.Threading.Tasks;

namespace csharpnaijaTutorial

{

    class Program

    {

        static async Task Main(string[] args)

        {

            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 to a FileStream.

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

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

We created a new file for writing. The bytes are written to the newly created file with the Write() method.

Reading Image using FileStream in C#

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

using System;

using System.IO;

namespace csharpnaijaTutorial

{

    class Program

    {

        static void Main(string[] args)

        {

            var fileName = @"C:\Users\csharpnaija\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 advances the 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 to read 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.

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

 

Reference

1.     Zetcode

2.     Tutlane

3.     GeeksForGeeks

 

Comments

Popular posts from this blog

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...