Text file handling in C#

A file is a piece of information stored on your computer with a specific name. Every file is converted as a sequence of bytes known as file stream when opened for reading or writing.

Text file handling in C#

A file is a piece of information stored on your computer with a specific name. Every file is converted as a sequence of bytes known as file stream when opened for reading or writing.

Fortunately, the System.IO namespace comes with everything we could need for text file handling. For performing file operations, you should first add a reference to System.IO namespace.

Creating a text file

A file can be created using the Create() method. It takes file path as the first parameter. This method created a new file under the specified location only if a file in the same name does not exist.

File.Create(@"D:/My_New_File.txt");

This will create a new file named  My_New_File.txt in the D drive.

Writing data to a text file

There are several methods to write data to a file. Some of them are:

METHODEXPLANATIONExample
WriteAllText()
WriteAllText(string path, string data)
Creates a new file if does not exist and writes the specified data to it. If the file already exists, it will be overwritten.

File.WriteAllText("D:/myfile.txt","Hello World");
WriteAllLines()
WriteAllLines(string path, string[] data)
Creates a new file, writes the specified array to the file and then closes it.File.WriteAllLines("D:/myfile.txt",myarray);
WriteAllBytes()
WriteAllBytes(string path, byte[] data)
Creates a new file if does not exist and writes the specified byte array to the file. If the file already exists, It will be overwritten.File.WriteAllBytes("D:/myfile.txt",bytearray);

Share Tweet Send
Loading...
You've successfully subscribed to Geekinsta
Great! Next, complete checkout for full access to Geekinsta
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.