In C#, the FileStream class offers a stream for handling file operations, enabling both synchronous and asynchronous reading and writing tasks. Utilizing the FileStream class simplifies the process of reading from and writing to files.
The <style> element is designed with a background of a linear gradient from #374151 to #1f2937. It has a border-radius of 12px, along with 40px padding and a 20px vertical margin. The content is centered within this diagram. The icon within has a font size of 3rem and a 10px bottom margin. Text inside this element is styled in #9ca3af color with a font size of 1rem.
In C#, a stream represents an uninterrupted movement of information moving between a starting point and an endpoint, which could include storage devices, memory, communication channels, or various software components. Within the context of C#, when employing the FileStream, activities are performed at the level of individual bytes. For managing textual data more conveniently, the StreamWriter and StreamReader classes can be utilized.
Syntax:
The most straightforward method to instantiate a FileStream object is by utilizing the subsequent constructor overload.
Public FileStream(string path, FileMode mode, FileAccess access, FileShare share);
This overload creates a new System.IO.FileStream instance with the given path, creation mode, read/write permission, and sharing permission.
- Path: It represents an absolute or relative path to the file that the present FileStream object will encapsulate.
- mode: It represents a variable that determines how to open or create the file.
- access: It represents a constant that is utilized to specify how the file needs to be accessed through the FileStream object.
- Share: It represents an integer constant that specifies how the file is shared between processes.
To utilize the FileStream class, it is necessary to import the System.IO namespace and instantiate a FileStream Object to either open an existing file or generate a new one.
FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);
FileMode:
In the C# filestream, the FileMode indicates the method by which the operating system should access the file. It consists of the following components.
| Function | Description |
|---|---|
| Append | It is used to open the file if it exists or create a new file. If the file already exists, position the cursor at the end of the file. |
| Create | It is used to tell the operating system to make a new file. If the file already exists, the old file will be replaced. |
| CreateNew | It is used to open a new file, and if the file exists, it throws an IOException. |
Open |
It is used to open an existing file. |
| Open or Create | It is used to open an existing file. If it is not present, it will create a new file. |
| Truncate | It is used to open an existing file and truncate all the stored data, which helps to decrease the file size to 0. |
FileAccess:
In C#, the FileAccess provides permissions to open files in Read, ReadWrite, or Write mode.
| Function | Description |
|---|---|
Read |
It is used to provide read access to the file. The data can be read from it. It is also used to write for read/write access. |
| Write | It allows Write permission to the file, and the data to be written to it. It should be used with Read for read/write permission. |
| ReadWrite | It gives read and write access to the file, so the data can be read and written to it. |
FileShare:
In C# programming, the FileShare class establishes a file with the specified sharing permissions.
| Functions | Description |
|---|---|
| Delete | It is used to give permission for the future deletion of the file. |
| Inheritable | It is used to pass the inheritance to the child process. |
None |
It denies the sharing of the current files. |
Read |
It gives permission for future opening of the file to read. |
| ReadWrite | It gives permission for further opening of the file to read or write. |
| Write | It allows further opening of the file in write mode. |
C# FileStream Example to write a single byte into a file
Let's explore a basic illustration of utilizing the FileStream class to append a solitary byte of information to a file. In this scenario, the OpenOrCreate file mode is employed, enabling both reading and writing functionalities.
Example
using System;
using System.IO;
public class FileStreamExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\b.txt", FileMode.OpenOrCreate);//creating file stream
f.WriteByte(65); //writing byte into stream
f.Close(); //closing stream
}
}
Output:
Explanation:
In this instance, we access or generate a file named b.txt on the E drive through the implementation of FileStream. Utilizing WriteByte(65) enables the writing of a single byte with a value of 65, corresponding to the character A in ASCII. If the file already exists, the new byte is appended at the start of the file. To conclude, the Close method is invoked to persist modifications and free up the system resources linked to the file.
C# FileStream Example to write multiple bytes into a file
Let's examine another instance of writing multiple bytes of information to a file by employing a loop in C#.
Example
using System;
using System.IO;
public class FileStreamExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\b.txt", FileMode.OpenOrCreate);
for (int i = 65; i <= 90; i++)
{
f.WriteByte((byte)i);
}
f.Close();
}
}
Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Explanation:
In this illustration, we initiate the opening or creation of a file named b.txt in the E drive through the utilization of FileStream. Within the for loop, byte values ranging from 65 to 90 are included, corresponding to the uppercase letters A through Z in ASCII. These values are sequentially written into the file. Subsequently, the stream is terminated to conclude the writing process and release resources.
C# FileStream example to read all bytes from a file
Let's explore an instance involving the FileStream class illustrating the process of extracting information from a file. In this scenario, we will employ the ReadByte function from the FileStream class, which provides a single byte of data. Subsequently, we will iterate through a loop to retrieve all the bytes present in the file.
Example
using System;
using System.IO;
public class FileStreamExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\b.txt", FileMode.OpenOrCreate);
int i = 0;
while ((i = f.ReadByte()) != -1)
{
Console.Write((char)i);
}
f.Close();
}
}
Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Explanation:
In this instance, we initiate the process of opening or generating a b.txt file located on the E drive using FileStream. The file is read sequentially, one byte at a time, utilizing the ReadByte method, which signals the end of the file by returning -1. Each byte is then displayed as a character on the console, enabling the application to display the file's contents. Subsequently, the stream is closed to free up resources.
C# FileStream with StreamWriter and StreamReader
In C#, FileStream provides a mechanism for direct byte-level interaction with files, whereas StreamWriter and StreamReader are classes at a higher level that streamline the process of writing to and reading from text files.
- StreamWriter: This class is frequently employed for writing characters or strings to a file, handling the conversion to bytes internally.
- StreamReader: This class is typically utilized for reading text from a file, reversing the byte-to-character conversion process.
They can both be utilized in conjunction with a FileStream, which dictates the method by which the file is opened, generated, and interacted with.
C# FileStream Example with StreamWriter and StreamReader
Let's explore a scenario to demonstrate the FileStream using StreamWriter and StreamReader in C#.
Example
using System;
using System.IO;
class FileStreamReaderExample
{
static void Main()
{
string path = "File1.txt";
if (!File.Exists(path))
{
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine("Hello, this is a default text in the file.");
writer.WriteLine("You can add more content here.");
}
}
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (StreamReader reader = new StreamReader(fs))
{
string content = reader.ReadToEnd();
Console.WriteLine("File Content:");
Console.WriteLine(content);
}
}
}
Output:
File Content:
Hello, this is a default text in the file.
You can add more content here.
Explanation:
In this illustration, we verify the existence of a file named File1.txt. Should the file be absent, it is generated and populated with two lines of text using the StreamWriter class. Subsequently, the file is accessed once more using a FileStream object, and its entire content is extracted via a StreamReader object before being displayed on the console. Lastly, the script confirms the file's presence, adds default text if the file is missing, and proceeds to retrieve and display the file's content.
FileStream with Buffering in C#
In C# development, the buffer serves as a temporary storage space crucial for temporarily retaining data during its movement between different locations, like memory and disk. The utilization of buffering within a FileStream is instrumental in minimizing I/O workload by lessening the frequency of direct disk interactions. Upon instantiation of a FileStream instance, it is straightforward to designate a buffer size, determining the amount of data temporarily held in memory before being written or post-read.
C# FileStream Example using Buffering
Let's consider an illustration to showcase the FileStream with buffering in C#.
Example
using System;
using System.IO;
using System.Text;
class C# Tutorial
{
static void Show()
{
string path = "buffered2.txt";
string info = "BufferedStream makes file I/O more efficient.";
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamWriter writer = new StreamWriter(bs))
{
writer.WriteLine(info);
}
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader reader = new StreamReader(bs))
{
Console.WriteLine("File Contains: \n" + reader.ReadToEnd());
}
}
static void Main()
{
Show();
}
}
Output:
File Contains:
BufferedStream makes file I/O more efficient.
Explanation:
In this instance, we create a file named buffered2.txt by employing the FileStream within BufferedStream and StreamWriter. Subsequently, we access the identical file by utilizing BufferedStream and StreamReader to extract the data and display it on the screen. Ultimately, we employ the Show function to execute all file tasks, which is called by the Main method.
Features of the FileStream in C#
There are several features of the FileStream in C#. Some of them are as follows:
- The FileStream in C# gives direct and byte-level access to files on the disk. It is suitable to manage both text and binary data.
- In C#, FileStream allows us to open or create a file using the FileMode and FileAccess enumerations.
- The FileStream provides support for both synchronous and asynchronous file operations, which allows us to choose between code simplicity and performance.
- We can use the FileStream to work directly with bytes or wrap it with several functions, such as StreamReader, StreamWriter, BinaryReader, or BinaryWriter. These functions help to handle text or binary data.
- It can work effectively across all platforms that are supported by the .NET Framework, which ensures portability of file-handling operations.
Conclusion
In summary, the C# FileStream class provides a straightforward and efficient approach to working with files. It allows us to perform tasks such as reading, writing, and manipulating files with precision, offering control over various aspects like file modes, access rights, buffering, sharing choices, and more. This class guarantees optimal performance and dependability in file operations by accommodating both synchronous and asynchronous tasks. Ultimately, FileStream serves as a fundamental component for effective and safe file handling across text, binary data, and large file datasets.
C# FileStream FAQs
Which namespace is utilized in the FileStream class in C#?
In C#, the System.IO namespace is frequently employed in the FileStream class. As a result, it is essential to incorporate System.IO into the program.
The common constructors of FileStream in C# include the following:
- ```
Public FileStream(string path, FileMode mode, FileAccess access, FileShare share);
- ```
FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);
- ```
using System;
using System.IO;
public class FileStreamExample
{
public static void Main(string args)
{
FileStream f = new FileStream("e:\\b.txt", FileMode.OpenOrCreate);//creating file stream
f.WriteByte(65); //writing byte into stream
f.Close; //closing stream
}
}
- ```
using System;
using System.IO;
public class FileStreamExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\b.txt", FileMode.OpenOrCreate);
for (int i = 65; i <= 90; i++)
{
f.WriteByte((byte)i);
}
f.Close();
}
}
- ```
ABCDEFGHIJKLMNOPQRSTUVWXYZ
There are several common constructors of the FileStream in C#. These are as follows:
- FileStream(string path, FileMode mode);
- FileStream(string path, FileMode mode, FileAccess access);
- FileStream(string path, FileMode mode, FileAccess access, FileShare share);
3) What is the process of accessing a file with FileStream in C#?
In C#, the .Read() method can be employed to input bytes into a buffer.
Example:
byte buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
4) Is it possible to utilize the FileStream class for handling asynchronous file operations in C#?
Yes, FileStream does offer asynchronous functionality through methods like ReadAsync() and WriteAsync(). This can significantly improve performance for input/output bound applications.
5) When attempting to open a non-existent file using FileMode.Open in C#, an exception of type FileNotFoundException will be thrown. This exception indicates that the specified file could not be found at the given path. It's important to handle this exception appropriately in order to prevent the application from crashing and to provide a better user experience.
In C#, a FileNotFoundException is raised. To ensure the file is created if it is missing, the OpenOrCreate method must be utilized.