Handling files is extremely important, especially for enterprise applications. To support this feature, Microsoft .NET Framework provides the System.IO namespace to offer various classes, allowing developers to handle I/O.
File I/O in C# is what?
In addition, the System.IO namespace also provides features to support operations with files and directories in the operating system's file system. In this article, Mytour will introduce you to what File I/O in C# is, as well as how to work with classes in the System.IO namespace to read and write data to files.
1. Using the File class to read and write data.
1.1. Reading data from a file.
1.2. Writing data to a file.
2. Using the File and FileInfo classes to manipulate files.
2.1. Using the File class to manipulate files.
2.2. Using the FileInfo class to manipulate files.
2.3. Initializing the FileInfo class.
3. Using the DirectoryInfo and Directory classes to manipulate directories.
3.1. Using the Directory class to manipulate directories.
3.2. Using the DirectoryInfo class to manipulate directories.
3.3. Initializing the DirectoryInfo class.
1. Using the File class to read and write data
The File class of the System.IO namespace provides various static methods that allow developers to perform direct reading and writing of files. Typically, to read data from a file, we need:
- A file to be processed.
- Creating a file stream.
- Specifying a data buffer for the file.
- Releasing the processed file.
1.1. Reading data from a file
Below is a list of methods to read data from a file in C#:
- The ReadAllText method reads the data of the file:
string filePath = @'C:\MyData\TestFile.txt';
string testData = File.ReadAllText(filePath);
- The ReadAllLines method reads all content of the file and stores each line creating a new index in a string array:
string filePath = @'C:\MyData\TestFile.txt';
string[] testDataLineByLine = File.ReadAllLines(filePath);
- The method ReadAllBytes reads the content of the file as binary data and stores the data in a byte array.
string filePath = @'C:\MyData\TestFile.txt';
byte[] testDataRawBytes = File.ReadAllBytes(filePath);
Each method above allows developers to read the content of the file and load it into memory. The ReadAllText method allows developers to store the entire file in memory in a single operation. The ReadAllLines method reads line by line into an array.
1.2. Writing data to a file
The File class also provides methods to write various types of data to a file. For each type of data you write, the File class provides 2 methods.
If the specified file does not exist, the WriteXXX methods create a new file with the new data. If the file exists, the WriteXXX methods overwrite the existing file with the new data.
If the specified file does not exist, the AppendXXX methods also create a new file with the new data. If the file exists, the new data is appended to the end of the existing file.
Below are the details of the methods for writing data to a file:
- The method 'WriteAllText' allows developers to write the content of a string variable to a file. If the file exists, the content of the file will be overwritten. The example below illustrates how to write the content of a string named settings to a new file named settings.txt:
string filePath = @'C:\MyData\TestFile.txt';
string data = 'C# Corner MVP & Microsoft MVP;';
File.WriteAllText(filePath, data);
- The method
'WriteAllLines' allows developers to write the content of a string array to a file. Each item in the string array represents a new line in the new file.
string filePath = @'C:\MyData\TestFile.txt';
string[] data = { 'MCT', 'MCPD', 'MCTS', 'MCSD.NET', 'MCAD.NET', 'CSM' };
File.WriteAllLines(filePath, data);
- The method 'AppendAllText' enables developers to append the content of a string variable to the end of an existing file.
string filePath = @'C:\MyData\TestFile.txt';
string data = 'Also Certified from IIT Kharagpur';
File.AppendAllText(filePath, data);
- The method 'AppendAllLines' allows developers to append the content of a string array to the end of an existing file.
string filePath = @'C:\MyData\TestFile.txt';
string[] otherData = { 'Worked with Microsoft', 'Lived in USA' };
File.AppendAllLines(filePath, otherData);
2. Using the File and FileInfo Classes to Manipulate Files
File manipulation is as crucial as file creation. Many applications require the ability to interact with files stored in the file system. For example, copying a file from one directory to another for processing.
By utilizing the File and FileInfo classes, developers can achieve this.
2.1. Using the File Class to Manipulate Files
The File class encompasses various static methods that developers can utilize to perform basic file operations. Below are details of some methods using the File class to manipulate files:
- The 'Copy' method allows developers to copy an existing file to a different location in the file system.
string sourceFilePath = @'C:\MyData\TestFile.txt';
string destinationFilePath = @'C:\temp\Data.txt';
bool overWrite = true;
File.Copy(sourceFilePath, destinationFilePath, overWrite);
Note: The overwrite parameter passed to the Copy method call indicates that the copying process will overwrite the existing file if it exists at the destination path. If the Copy method call is incorrect and the file already exists, then the Common Language Runtime (CLR) will throw a System.IO.IOException.
- The 'Delete' method removes an existing file from the file system.
string sourceFilePath = @'C:\MyData\TestFile.txt';
File.Delete(sourceFilePath);
- The 'Exists' method checks if a file exists in the file system.
string sourceFilePath = @'C:\MyData\TestFile.txt';
bool doesFileExist = File.Exists(sourceFilePath);
- The 'GetCreationTime' method contains a date-time stamp describing when the file was created from the metadata associated with the file.
string sourceFilePath = @'C:\MyData\TestFile.txt';
DateTime fileCreatedOn = File.GetCreationTime(sourceFilePath)
2.2. Using the FileInfo class to manipulate files
Unlike the File class, the FileInfo class provides variant members that you can use to manipulate existing files. While the File class offers static methods for direct operations, the FileInfo class acts as a representation of the file's physical memory.
2.3. Initializing the FileInfo class
string sourceFilePath = @'C:\MyData\TestFile.txt';
FileInfo fInfo = new FileInfo(sourceFilePath);
Once the FileInfo instance is created, you can utilize its properties and methods to interact with the file. Below is a detailed list of properties and methods for initializing the FileInfo class:
- The 'CopyTo' method allows developers to copy the existing file to another directory in the file system.
string sourceFilePath = @'C:\MyData\TestFile.txt';
string destinationFilePath = @'C:\temp\Data.txt';
bool overwrite = true;
FileInfo fInfo = new FileInfo(sourceFilePath);
fInfo.CopyTo(destinationFilePath, overwrite);
Note: The overwrite parameter in the CopyTo method indicates that the copying process will overwrite the existing file if it exists at the specified destination file path. If an incorrect CopyTo method is passed and the file already exists, the CLR will throw a System.IO.IOException.
- The 'Delete' method allows for deleting a file.
string sourceFilePath = @'C:\MyData\TestFile.txt';
FileInfo fInfo = new FileInfo(sourceFilePath);
fInfo.Delete();
- The 'DirectoryName' property retrieves the directory path to the file.
string sourceFilePath = @'C:\MyData\TestFile.txt';
FileInfo fInfo = new FileInfo(sourceFilePath);
string directoryPath = fInfo.DirectoryName;
// returns C:\MyData
- The 'Exists' method allows developers to determine whether the specified file exists in the file system.
string sourceFilePath = @'C:\MyData\TestFile.txt';
FileInfo fInfo = new FileInfo(sourceFilePath);
bool filesExists = fInfo.Exists;
- The 'Extension' property retrieves the file extension.
string sourceFilePath = @'C:\MyData\TestFile.txt';
FileInfo fInfo = new FileInfo(sourceFilePath);
bool filesExtn = fInfo.Extension;
- The 'Length' property allows developers to retrieve the length of the file in bytes.
string sourceFilePath = @'C:\MyData\TestFile.txt';
FileInfo fInfo = new FileInfo(sourceFilePath);
long length = fInfo.Length;
3. DirectoryInfo and Directory for Directory Operations
In the file system of the operating system, files are organized and grouped within directories. Therefore, interacting and manipulating the directory structure of the file system is extremely important.
Interacting with directories involves checking if a directory exists before writing files or deleting the directory after the process is complete. The .NET Framework class library provides the Directory and DirectoryInfo classes to perform these operations.
3.1. Using Directory Class for Directory Operations
Similar to the File class, the Directory class provides static methods that allow you to interact with directories without initializing objects related to the directory in code.
- The 'CreateDirectory' method creates a new directory on the file system.
string sourceDirPath = @'C:\MyData\Data';
Directory.CreateDirectory(sourceDirPath);
- The 'Delete' method deletes the directory at the specified path.
string sourceDirPath = @'C:\MyData\Data';
bool deleteRecursively = true;
Directory.Delete(sourceDirPath, deleteRecursively);
Note: The deleteRecursively parameter is passed to the Delete method to specify whether any existing content in this directory should be deleted. If incorrectly passed to the Delete method and the directory is not empty, then CLR will throw a System.IO.IOException.
- The 'Exists' method determines whether the directory exists on the file system or not.
string sourceDirPath = @'C:\MyData\Data';
bool tempDataDirectoryExists = Directory.Exists(sourceDirPath);
- The 'GetDirectories' method retrieves a list of all subdirectories within a specific directory on the file system.
string sourceDirPath = @'C:\MyData\Data';
string[] subDirectories = Directory.GetDirectories(sourceDirPath);
- The 'GetFiles' method retrieves a list of all files within a specific directory on the file system.
string sourceDirPath = @'C:\MyData\Data';
string[] files = Directory.GetFiles(sourceDirPath);
The DirectoryInfo class provides variant members, allowing you to access directory metadata and manipulate the directory structure.
Using DirectoryInfo to Manipulate Directories
The DirectoryInfo class acts as an in-memory representation of a directory. Before accessing the properties and executing the methods of the DirectoryInfo class, we need to create an instance of it.
Initializing DirectoryInfo
string sourceDirPath = @'C:\MyData\Data';
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
When creating an instance of the DirectoryInfo class, you can use its properties and methods to interact with directories. Below are details describing some properties and methods of the DirectoryInfo class:
- The 'Create' method creates a new directory on the file system.
string sourceDirPath = @'C:\MyData\Data';
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
directory.Create();
- The 'Delete' method deletes the directory at the specific path.
string sourceDirPath = @'C:\MyData\Data';
bool deleteRecursively = true;
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
directory.Delete(deleteRecursively);
Note: The recursivelyDeleteSubContent parameter is passed to the Delete method call, indicating whether the deletion process should remove any existing content within the directory. If an incorrect command is passed to the Delete method, and the directory is not empty, then the CLR will throw a System.IO.IOException.
- The 'Exists' method determines whether the directory exists on the file system or not.
string sourceDirPath = @'C:\MyData\Data';
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
bool directoryExists = directory.Exists
- The 'FullName' property retrieves the full path to the directory. The example below illustrates how to get the full path to the 'tempData' directory.
string sourceDirPath = @'C:\MyData\Data';
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
string fullPath = directory.FullName;
- The 'GetDirectories' method retrieves a list of all subdirectories within a specific directory on the file system. In contrast to the static method File.GetDirectories, this variant of the method returns an array of DirectoryInfo type, allowing you to use the properties of DirectoryInfo for each subdirectory.
string sourceDirPath = @'C:\MyData\Data';
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
DirectoryInfo[] subDirectories = directory.GetDirectories();
- The 'GetFiles' method retrieves a list of all files within a specific directory on the file system. In contrast to the static method File.GetFiles, this variant of the method returns an array of FileInfo type, allowing you to use the properties of FileInfo for each file.
string sourceDirPath = @'C:\MyData\Data';
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
FileInfo[] subFiles = directory.GetFiles();
Depending on your requirements and the need for simple line-by-line code access to manipulate a directory, either the Directory or DirectoryInfo class will meet your needs.
This article above by Mytour.vn just introduced you to what file I/O in C# is. If there are any questions or inquiries that need clarification, readers can leave their comments below the article. Additionally, readers can refer to some articles already available on Mytour to learn more about how to handle exceptions in C#.