In c#, FileStream is a class of System.IO namespace, and it will provide a stream for file operations. By using FileStream, we can perform read and write operations on files.
Now, we will see how to use FileStream class in c# to write and read text from a file with examples.
Following is the example of writing a text to file using the FileStream object in c#.
If you observe the above example, we imported a System.IO namespace to access File & FileStream objects to delete, create and write a text to file. Here, we added text to the file by converting it into bytes format using the AddTexttoFile method.
When we execute the above example, it will create a new “Test.txt” file in the D drive with the required text as shown below.
This is how we can create, delete and add text to files using File & FileStream objects in c#.
Following is the example of reading text from a file using the FileStream object in c#.
If you observe the above example, we imported a System.IO namespace to access File & FileStream objects to check and read text from a file.
When you execute the above example, it will read the text from “Test.txt” file in D drive and return the result as shown below.
This is how we can use FileStream class in c# to write or read data from the file in the file system.