Examples of using the FileStream class without using additional streams (decorators, adapters)
Before exploring this topic, it is recommended that you familiarize yourself with the following topics:
- Stream concept. Stream architecture in C#. Basic storage streams. Streams with decorators. Adapters streams
- Hierarchy of streams with basic storages. The FileStream class
The FileStream class can be applied standalone without the need for additional adapters streams or decorators. For this, the class has all the necessary tools (methods). The main methods the class inherits from the base class Stream.
Contents
- 1. An example of reading/writing a double to a file. Using FileStream
- 2. An example of writing / reading an array of numbers of type int[]
- 3. An example of writing/reading an array of strings string[]
- 4. An example of writing/reading an array of instances of the Car class (car)
- 5. An example of rewriting in a file the values of an array of type double[], which are located at even positions (0, 2, 4, …). Demonstration of using the Seek() method
- Related topics
Search other resources:
1. An example of reading/writing a double to a file. Using FileStream
The example demonstrates how to use the tools of the FileStream class and the base Stream class to write/read a double number to a file.
using System; using System.IO; using System.Text; namespace ConsoleApp10 { class Program { static void Main(string[] args) { // An example of writing/reading a number of type double to the file "file1.bin". // Methods Read(), Write() of FileStream class // 1. Writing a number to a file // 1.1. Create a file named "file1.bin" for writing using (FileStream fs = new FileStream("file1.bin", FileMode.Create, FileAccess.Write)) { // 1.2. Specified number double x = 2.55; // 1.3. Convert x to array of type byte[] byte[] bt = Encoding.Default.GetBytes(x.ToString()); // 1.4. Writing the number x to a file fs.Write(bt, 0, bt.Length); } // 2. Read number from file - Read() method using (FileStream fs2 = new FileStream("file1.bin", FileMode.Open, FileAccess.Read)) { // 2.1. Declare a buffer array into which data will be read byte[] bt2 = new byte[10]; // 10 bytes is enough for a double // 2.2. Read number from file into bt2 array fs2.Read(bt2, 0, bt2.Length); // 2.3. Convert bt2 to type string - to string st string st = Encoding.Default.GetString(bt2); // 2.4. Convert st to x2 of type double double x2 = Convert.ToDouble(st); // 2.5. Display x2 Console.WriteLine("x2 = {0}", x2); // x2 = 2.55 } } } }
⇑
2. An example of writing / reading an array of numbers of type int[]
The example demonstrates writing an array of type int[] to a file and reading it. The program code uses the Read(), Write() methods of the base Stream class. Since the Read(), Write() methods require data to be represented as an array of bytes of the byte[] type, the capabilities of the BitConverter class are used to perform conversion operations.
using System; using System.IO; namespace ConsoleApp10 { class Program { static void Main(string[] args) { // Writing an array of numbers of type int [] to the file "array.bin" using (FileStream fs = new FileStream("array.bin", FileMode.Create, FileAccess.Write)) { // The array to be written to a file int[] AI = { 1, 3, 8, 4, 2, 6 }; // Additional buffer of byte[] type byte[] AB; // First, you need to write down the number of numbers in the array, // for this you can use the BitConverter class. // Represent AI.Length as a sequence of bytes AB = BitConverter.GetBytes(AI.Length); fs.Write(AB, 0, AB.Length); // Loop of elementwise writing of array numbers for (int i = 0; i < AI.Length; i++) { AB = BitConverter.GetBytes(AI[i]); fs.Write(AB, 0, AB.Length); } } // Reading an array of numbers of type int[] from the file array.bin using (FileStream fs = new FileStream("array.bin", FileMode.Open, FileAccess.Read)) { int[] AI2; // array - result byte[] AB2; // additional buffer int count; // number of elements in array AI2 // Count the number of numbers AB2 = new byte[sizeof(int)]; // allocate memory for number of type int fs.Read(AB2, 0, AB2.Length); count = BitConverter.ToInt32(AB2, 0); // count the number of elements in the array AI2 // Allocate memory for AI2 array AI2 = new int[count]; // Loop of element-by-element reading of numbers into the array AI2 for (int i = 0; i < AI2.Length; i++) { // Use preallocated memory for a number of type int fs.Read(AB2, 0, AB2.Length); AI2[i] = BitConverter.ToInt32(AB2, 0); } // Print the array AI2 for verification for (int i = 0; i < AI2.Length; i++) { Console.Write("{0} ", AI2[i]); } } } } }
The result of the program
1 3 8 4 2 6
⇑
3. An example of writing/reading an array of strings string[]
The example demonstrates writing an array of strings to a file and reading it.
using System; using System.IO; using System.Text; namespace ConsoleApp10 { class Program { static void Main(string[] args) { // Writing an array of strings of type string [] to the "strings.bin" file using (FileStream fw = new FileStream("strings.bin", FileMode.Create, FileAccess.Write)) { // The array to write to the file string[] AS = { "Delphi", "Java", "C#", "Python", "C++" }; // Additional buffer of byte[] type byte[] AB; // First you need to write down the number of lines, // you can use the BitConverter class for this. AB = BitConverter.GetBytes(AS.Length); fw.Write(AB, 0, AB.Length); // The loop for writing lines for (int i = 0; i < AS.Length; i++) { // First write the length of the string AB = BitConverter.GetBytes(AS[i].Length); fw.Write(AB, 0, AB.Length); // To write a string, you need to use the Encoding class from // namespace System.Text, because the string can be written // in different encoding systems. AB = Encoding.UTF8.GetBytes(AS[i]); // UTF-8 encoding system fw.Write(AB, 0, AB.Length); } } // Reading strings of type string[] from the "strings.bin" file using (FileStream fr = new FileStream("strings.bin", FileMode.Open, FileAccess.Read)) { string[] AS2; // the resulting array byte[] AB2; // auxiliary byte buffer int count; // number of elements in array AS2 int len; // additional variable - the length of the string // Read the number of lines - count AB2 = new byte[sizeof(int)]; // allocate memory for number of int type fr.Read(AB2, 0, AB2.Length); count = BitConverter.ToInt32(AB2, 0); // Allocate memory for array AS2 AS2 = new string[count]; // A cycle of element-by-element reading of numbers into the AS2 array. for (int i = 0; i < AS2.Length; i++) { // Read the length of the AS2[i] string in bytes. AB2 = new byte[sizeof(int)]; fr.Read(AB2, 0, AB2.Length); len = BitConverter.ToInt32(AB2, 0); // len - the length of string AS2[i] // Read the string AS2[i] AB2 = new byte[len]; // allocate memory for len bytes fr.Read(AB2, 0, AB2.Length); // read to the AB2 buffer // converting string <= byte[] AS2[i] = ""; for (int j = 0; j < AB2.Length; j++) AS2[i] = AS2[i] + (char)AB2[j]; } // Print array AS2 for checking for (int i = 0; i < AS2.Length; i++) Console.WriteLine(AS2[i]); } } } }
The result of the program
Delphi Java C# Python C++
⇑
4. An example of writing/reading an array of instances of the Car class (car)
Task. The class Car is specified, that contains the following data members:
- model – car brand;
- volume – engine volume;
- year – year of issue.
Also, the Car class contains properties for accessing data members and special class functions:
- constructor;
- properties Model, Volume, Year.
It is necessary to implement writing an array of instances of the Car[] type to a file and reading it with the subsequent output of the result.
Solution. The program text that solves this problem is as follows.
using System; using System.IO; using System.Text; namespace ConsoleApp10 { // Class describing the car class Car { // Internal data members of the class private string model; private float volume; private int year; // Constructor public Car(string model, float volume, int year) { this.model = model; this.volume = volume; this.year = year; } // Access methods public string Model { get { return model; } set { model = value; } } public float Volume { get { return volume; } set { volume = value; } } public int Year { get { return year; } set { year = value; } } } class Program { static void Main(string[] args) { // Writing an array of Car[] classes to the "cars.bin" file using (FileStream fw = new FileStream("cars.bin", FileMode.Create, FileAccess.Write)) { // The array to write to the file Car[] cars = { new Car("Volvo", 2.8f, 2018), new Car("Renault", 0.9f, 2017), new Car("Audi", 12.2f, 2030) }; // Additional buffer of byte[] type byte[] AB; // First you need to write down the number of elements of the cars array AB = BitConverter.GetBytes(cars.Length); fw.Write(AB, 0, AB.Length); // Loop for writing elements of array cars for (int i = 0; i < cars.Length; i++) { // 1. Write the model string // First, write the length of the string cars[i].Model AB = BitConverter.GetBytes(cars[i].Model.Length); fw.Write(AB, 0, AB.Length); // To write a string, you need to use the Encoding class // from the System.Text namespace AB = Encoding.Default.GetBytes(cars[i].Model); fw.Write(AB, 0, AB.Length); // 2. Write the volume AB = BitConverter.GetBytes(cars[i].Volume); fw.Write(AB, 0, AB.Length); // 3. Write the year of issue AB = BitConverter.GetBytes(cars[i].Year); fw.Write(AB, 0, AB.Length); } } // Reading an array of type Car[] from the "cars.bin" file using (FileStream fr = new FileStream("cars.bin", FileMode.Open, FileAccess.Read)) { Car[] cars2; // array - result byte[] AB2; // additional byte buffer int count; // the number of elements in the cars2 array int len; // additional variable - length of string // Read the number of elements in the array cars2 - count AB2 = new byte[sizeof(int)]; // allocate memory for number of int type fr.Read(AB2, 0, AB2.Length); count = BitConverter.ToInt32(AB2, 0); // Allocate memory for array cars2 cars2 = new Car[count]; // Declare additional variables that will duplicate the internal data of the class string model; // car model float volume; // engine volume int year; // year of issue // Loop of element-by-element reading of instances of the Car type into the cars2 array for (int i = 0; i < cars2.Length; i++) { // 1. Read string Model // Read the length of the string cars2 [i] .Model in bytes AB2 = new byte[sizeof(int)]; fr.Read(AB2, 0, AB2.Length); len = BitConverter.ToInt32(AB2, 0); // len - length of string cars2[i].Model // Read the string AB2 = new byte[len]; // allocate memory for len bytes fr.Read(AB2, 0, AB2.Length); // read to the buffer AB2 // converting string <= byte[] model = ""; for (int j = 0; j < AB2.Length; j++) model += (char)AB2[j]; // 2. Read volume AB2 = new byte[sizeof(float)]; fr.Read(AB2, 0, AB2.Length); volume = BitConverter.ToSingle(AB2); // 3. Read year AB2 = new byte[sizeof(int)]; fr.Read(AB2, 0, AB2.Length); year = BitConverter.ToInt32(AB2); // 4. Create the instance of cars2[i] class cars2[i] = new Car(model, volume, year); } // Display the array cars2 for (int i = 0; i < cars2.Length; i++) { Console.WriteLine("Model = {0}, Volume = {1}, Year = {2}", cars2[i].Model, cars2[i].Volume, cars2[i].Year); } } } } }
The result of the program
Model = Volvo, Volume = 2.8, Year = 2018 Model = Renault, Volume = 0.9, Year = 2017 Model = Audi, Volume = 12.2, Year = 2030
⇑
5. An example of rewriting in a file the values of an array of type double[], which are located at even positions (0, 2, 4, …). Demonstration of using the Seek() method
The example demonstrates overwriting data directly in a file. As an example, an array of numbers of the double[] type is written and read. Numbers that are in even positions are replaced. Simultaneous reading of data from a file and their writing to a file is possible in the FileAccess.ReadWrite access mode.
using System; using System.IO; namespace ConsoleApp10 { class Program { static void Main(string[] args) { // Writing an array of type double[] to the file "doubles.bin" using (FileStream fw = new FileStream("doubles.bin", FileMode.Create, FileAccess.Write)) { // The array to write to the file double[] AD = { 2.8, 3.3, 1.7, 3.8, 4.3, 6.1 }; // Additional buffer of byte[] type byte[] AB; // First you need to write the number of elements of the AD array AB = BitConverter.GetBytes(AD.Length); fw.Write(AB, 0, AB.Length); // Loop for writing the elements of AD array for (int i = 0; i < AD.Length; i++) { AB = BitConverter.GetBytes(AD[i]); // byte[] <= double fw.Write(AB, 0, AB.Length); // fw <= byte[] } } // Overwrite numbers in a file that are placed in paired positions using (FileStream fs = new FileStream("doubles.bin", FileMode.Open, FileAccess.ReadWrite)) { // Count the number of elements in the array byte[] AB = new byte[sizeof(int)]; fs.Read(AB, 0, AB.Length); int count = BitConverter.ToInt32(AB); // The loop bypassing the elements in the file, elements at odd positions are skipped for (int i = 1; i <= count; i++) // if an odd position, then rewind the read/write pointer in the file if (i % 2 == 1) fs.Seek(sizeof(double), SeekOrigin.Current); // skip number of type double else { // write a random number from 0 to 10 to a paired position in the file double num = (double)(new Random()).Next(0, 10); AB = BitConverter.GetBytes(num); fs.Write(AB, 0, AB.Length); } } // Reading an array of type double[] from the file "doubles.bin" using (FileStream fr = new FileStream("doubles.bin", FileMode.Open, FileAccess.Read)) { double[] AD2; // resulting array byte[] AB2; // additional buffer int count; // number of elements in array AD2 // Read the number of elements in array AD2 - count AB2 = new byte[sizeof(int)]; // allocate memory for number of int type fr.Read(AB2, 0, AB2.Length); count = BitConverter.ToInt32(AB2, 0); // Allocate memory for AD2 array AD2 = new double[count]; // A loop of element-wise reading of double numbers from a file // and writing them to AD2 array for (int i = 0; i < AD2.Length; i++) { AB2 = new byte[sizeof(double)]; fr.Read(AB2, 0, AB2.Length); AD2[i] = BitConverter.ToDouble(AB2); } // Print the AD2 array for (int i = 0; i < AD2.Length; i++) Console.Write("{0:f1} ", AD2[i]); } } } }
The result of the program
2.8 5.0 1.7 5.0 4.3 8.0
⇑
Related topics
- Hierarchy of streams with basic storages. The FileStream class
- The FileStream class. Additional read/write options. Enumeration FileOpions. Examples
⇑