FileStream Class in c#

FileStream Class in c#

The FileStream class in the C# programming language is a built-in library with built-in functions and features from the System.IO namespace. The FileStream class is used to read and write data and information from existing files in a byte stream format. Unlike StreamReader and StreamWriter, the FileStream class is used to handle and manage text files. The FileStream C# class also operates on binary data files, making file streams in C# a flexible and reliable class method for reading, writing, and managing any type of file, whether binary or text.

FileStream Class in c#

The FileStream class allows users to perform detailed file operations at the bottom level when created in a C# program. This gives C# users greater control over read-write access, permissions, and proper management of large-volume files.

So, let’s take a closer look at the FileStream class in the C# programming language and all its functional features.

FileStream Overview in C#.

The FileStream class is commonly used in C# programs when a C# user needs to read or write data and information to a created or existing file byte-by-byte.

The FileStream class in C# programs provides more features and flexibility than StreamReader and StreamWriter by operating at the byte level. This means that the FileStream class in C# can handle and manage binary files (images, audio files, etc.) as well as text files.

C# users can use the FileStream class to implement both synchronous and asynchronous file handling operations.

Creating a FileStream Object.

C# users can create a FileStream object class in a program by specifying the desired file location path, the desired file access type, and the file open operation mode (read, write, and file mode) and other options such as file data information sharing.

Creating a FileStream Object Example.

using System;

using System.IO;

class FilestreamObject

{

static void Main()

{

string filePath = @”C:\path\filedata\myfile\sample.dat”;

try

{

/ Here we create a FileStream class to open the file for reading and writing purposes only.

using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))

{

Console.WriteLine(“FileStream class object created successfully.”);

}

}

catch (IOException exception)

{

Console.WriteLine(“Display file opening error. ” + exception.Message);

}

}

}

}

Special parameters for the FileStream class constructor object.

  • filePath – Here, C# users indicate the path to the file they want to open or create for file handling operations.
  • mode – This indicates how the desired file should be opened in your operating system. The FileMode of the file is defined here, which defines the mode in which it should be opened.
  • FileMode.Create – This creates a new file in the file handling process. If the file already exists, this command overwrites it.
  • FileMode.Open – This opens an existing file stored in your operating system.
  • FileMode.OpenOrCreate – If the file already exists in your computer system, this statement opens it; otherwise, it creates a new file for you.
  • FileMode.Append – If the file exists in your computer system, this statement opens it and goes to the bottom of the existing file. If the file does not exist in your computer system, it creates a new file.
  • access – This indicates the access type for accessing the file in your computer system. For example, it can be a read, write, or both method.

Here are some common features of FileAccess for file handling in the system.

  • FileAccess.Read – Here you open a file for reading in the file handling process.
  • FileAccess.Write – Here you open a file for writing data and information in the file handling process.
  • FileAccess.ReadWrite – Here you open a file for both read and write data operations in the file handling process.
  • Share – This provides the feature of sharing a file with others in the file handling process. For example,
  • FileShare.Read – Here you help another process read the file when a file is open in the file handling process.
  • FileShare.None – In this process, when a file is open in your system, no other process can access it.

Reading data using a FileStream in C#.

C# users can read byte-by-byte data information from an existing file using the FileStream class with file handling functions or methods like Read() and ReadByte().

Example of reading byte-by-byte data and information from a file.

using System;

using System.IO;

using System.Text;

class Program

{

static void Main()

{

string filePath = @”C:\path\filedata\myfile\sample.dat”;

try

{

//here it checks if the file exists or not

if (!File.Exists(filePath))

{

Console.WriteLine(“Search File is not found.”);

return;

}

//here it Open and read the file

using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))

using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))

{

string content = reader.ReadToEnd();

Console.WriteLine(content);

}

}

catch(UnauthorizedAccessException)

{

Console.WriteLine(“File access denied.”);

}

catch(IOException exception)

{

Console.WriteLine(“I/O File Error – ” + exception.Message);

}

catch (exception exception)

{

Console.WriteLine(“Unexpected File Error – ” + exception.Message);

}

}

}

Example of reading data into a byte array.

If you want to read multiple byte files at once in a C# user program, you can use the Read() function method to read the data into a byte array.

using System;

using System.IO;

using System.Text;

class Program

{

static void Main()

{

string filePath = @”C:\path\filedata\myfile\sample.dat”;

try

{

// Here it checks if the file exists or not

if (!File.Exists(filePath))

{

Console.WriteLine(“Search File is not found.”);

return;

}

using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))

{

byte[] buffer = new byte[1024];

int bytesRead;

//here we Read bytes into the buffer location

while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)

{

Console.WriteLine($”Read {bytesRead} bytes.”);

// here it Convert bytes to text and display information

string text = Encoding.UTF8.GetString(buffer, 0, bytesRead);

Console.WriteLine(text);

}

}

}

catch(UnauthorizedAccessException)

{

Console.WriteLine(“File access denied.”);

}

catch(IOException exception)

{

Console.WriteLine(“File I/O Error occurred. ” + exception.Message);

}

catch (exception exception)

{

Console.WriteLine(“Unexpected file Error.” + exception.Message);

}

}

}

Writing data to a file using the FileStream class.

C# users can use the FileStream class in file handling programs to create or write data to a file using methods like the Write() and WriteByte() functions.

Example of writing data to a file in bytes.

using System;

using System.IO;

class Program

{

static void Main()

{

string filePath = @”C:\path\filedata\myfile\Result.dat”;

try

{

using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))

{

byte[] data = new byte[] { 118, 99, 97, 110, 104, 101, 108, 112, 115, 117 }; // File data is – (Vcanhelpsu)

// Here it writes data to the result file

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

Console.WriteLine(“User-defined file data successfully written to the file.”);

}

}

catch (IOException exception)

{

Console.WriteLine(“File write data error occurred. ” + exception.Message);

}

}

}

}

Example writing a single byte.

C# users can also write byte information to individual files using the WriteByte() function method in file handling programs.

using System;

using System.IO;

class Program

{

static void Main()

{

string filePath = @”C:\path\filedata\myfile\Result.dat”;

try

{

using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))

{

fs.WriteByte(118); // here we Write byte representing to ‘V’ character

Console.WriteLine(“Byte written successfully to the result file.”);

}

}

catch(IOException exception)

{

Console.WriteLine(” error occurred during file operation. ” + exception.Message);

}

}

}

Seeking and positioning concepts in FileStream.

C# users can use the Seek() function method to move to a file position within a file stream. The Seek() function is used when C# users want to navigate to a particular location in a file before reading or writing to the current file.

Example of moving to a specific file location in a file.

using System;

using System.IO;

class Program

{

static void Main()

{

string filePath = @”C:\path\filedata\myfile\Result.dat”;

try

{

// here it checks if the file exists or not

if (!File.Exists(filePath))

{

Console.WriteLine(“Search File is not found.”);

return;

}

using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))

{

//here it Check file length before seeking

if (fs.Length <= 7)

{

Console.WriteLine(“Here This File does not contain enough for bytes.”);

return;

}

// here it Move to the 7th byte position in result file

fs.Seek(7, SeekOrigin.Begin);

//here it Read byte after file seeking

int byteRead = fs.ReadByte();

if (byteRead != -1)

{

Console.WriteLine($”Here the Byte at position 7 is – {byteRead}”);

Console.WriteLine($”Byte Character is – {(char)byteRead}”);

}

else

{

Console.WriteLine(“No file byte could be read here.”);

}

}

}

catch (IOException excption)

{

Console.WriteLine(“File system I/O Error – ” + excption.Message);

}

catch (UnauthorizedAccessException)

{

Console.WriteLine(“File seek access denied.”);

}

catch (Exception excption)

{

Console.WriteLine(“Unexpected file error displayed. ” + excption.Message);

}

}

}

}

Asynchronous I/O operations with FileStream.

In C# file handling, using asynchronous I/O file operations is often a better option to avoid blocking the main thread for large files. Which provides its users with asynchronous versions of file handling methods like FileStream, ReadAsync(), and WriteAsync().

Example of asynchronous file reading.

using System;

using System.IO;

using System.Text;

using System.Threading.Tasks;

class Program

{

static async Task Main()

{

string filePath = @”C:\path\filedata\myfile\Result.dat”;

try

{

// Here it checks if the file exists or not

if (!File.Exists(filePath))

{

Console.WriteLine(“Search File not found.”);

return;

}

using (FileStream fs = new FileStream(

filePath,

FileMode.Open,

FileAccess.Read,

FileShare.Read,

1024,

true)) // here it Enable async file operation mode

{

byte[] buffer = new byte[1024];

int bytesRead = await fs.ReadAsync(buffer, 0, buffer.Length);

Console.WriteLine($”Read file data {bytesRead} bytes asynchronously.”);

//here it Convert bytes to text

string content = Encoding.UTF8.GetString(buffer, 0, bytesRead);

Console.WriteLine(“File Content is.”);

Console.WriteLine(content);

}

}

catch(IOException exception)

{

Console.WriteLine(“I/O file operation Error.” + exception.Message);

}

catch(UnauthorizedAccessException)

{

Console.WriteLine(“file access denied.”);

}

catch (exception exception)

{

Console.WriteLine(“Unexpected file processing Error.” + exception.Message);

}

}

}

Closing a FileStream in File Handling.

The FileStream class implements IDisposable, which means that C# users must always properly close or dispose of the file after completing all file handling operations. The using File statement automatically closes the existing FileStream when your file handling program terminates execution of a block of program code, regardless of whether the file throws an exception.

Conclusion of the FileStream Class.

  • FileStream is the most basic and common method for working with file operations at the byte level in C# programs. It provides C# users with numerous functions, methods, and features for handling binary and text files, as well as large files.
  • FileStream is a more reliable, flexible, and detailed lower-level method than the StreamReader and StreamWriter methods, which are optimized for text-based file operations.
  • FileStream Use this feature in file handling when the C# user needs detailed control over how data is read and written to the file, especially when the C# user is working with non-text files.

Leave a Reply