In C#, the System.IO namespace provides base classes to work with physical files on disk. By using System.IO namespace we can easily create the files, write to the files and read the content from the files.
By using FileStream class we can read from and write to the files. First we will create the files and write some content to the file as shown below.
FileStream fs = File.Open(@"E:\test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
string str;
str = "This is content for File";
byte[] byteMsg = new UTF8Encoding(true).GetBytes(str);
fs.Write(byteMsg, 0, byteMsg.Length);
Console.WriteLine("Content written to file successfully");
Console.ReadLine();
File Class provides the Open method to open the physical file. File.Open() method expects parameters as physical file path, FileMode(Append, Create, CreateNew, Open, OpenOrCreate,Truncate), Fileaccess(Read, Write, ReadWrite) and FileShare.
The FileMode enumeration values are Append, Create, CreateNew, Open, OpenOrCreate,Truncate.
CreateNew: Creates a new file, if it already exists, an IOException is thrown.
Create: Creates a new file, if it already exists, it will be overwritten.
Open: Opens an existing file, if the file does not exist, a FileNotFoundException is thrown.
OpenOrCreate: Opens the file if it exists; otherwise, a new file is created.
Truncate: Opens a file and truncates the file to 0 bytes in size.
Append: Opens a file, moves to the end of the file, and begins write operations. If the file does not exist, a new file is created.
The above code creates file on E drive and writes content to that file and the output as shown below.
By using FileStream class we can read the content from file and the code is given below.
FileStream fs = File.Open(@"E:\test.txt", FileMode.Open, FileAccess.Read, FileShare.None);
int numBytesToRead = (int)fs.Length;
int numBytesRead = 0;
byte[] byteMsg = new byte[numBytesToRead];
fs.Read(byteMsg, numBytesRead, numBytesToRead);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(byteMsg));
Console.ReadLine();
The output to read the data from file is as shown below.