Microsoft's. NET Framework provides us with flow based I/O operations, which greatly simplifies the developer's work. Because we can operate on a series of common objects without having to worry about whether the I/O operation is related to the local file or to the data in the network. NET Framework primarily provides us with a System.IO namespace that basically contains all the classes related to I/O operations.
This article will introduce some basic file operation methods, including the file system in the directory and file operations, as well as the file read and write operations. By using the System.IO.DirectoryInfo class and the System.IO.FileInfo class, we can easily complete the directory and file-related operations, and by using the System.IO.StreamReader class and the System.IO.StreamWriter class We can easily complete the operation related to the reading and writing of the file.
Namespaces Overview
The table below shows some of the most important classes in the System.IO namespace, and by using these classes we can do basic file operations.
Table 1
Class name |
function and use |
BinaryReader, BinaryWriter |
Read and write binary data |
Directory, File, DirectoryInfo, and FileInfo |
Create, delete, and move directories and files, and obtain information about specific directories and files through properties |
FileStream |
Accessing files in random ways |
MemoryStream |
Accessing data stored in memory |
StreamReader, StreamWriter |
Read and write text data information |
StringReader, StringWriter |
Using string buffering to read and write text data information |
using the DirectoryInfo class and the FileInfo class
The base class for both the DirectoryInfo class and the FileInfo class is the FileSystemInfo class, which is an abstract class, which means that you cannot instantiate the class, you can only generate its subclasses by inheriting and instantiate its subclasses. However, you can use the various attributes defined by the class, and the following table shows the various properties that the class has defined.
Table 2
Property |
function and use |
Attributes |
Returns the attribute value associated with the file, using the FileAttributes enumeration type value |
CreationTime |
Returns the time the file was created |
Exists |
Check whether the file exists in the given directory |
Extension |
Returns the file name extension |
LastAccessTime |
Returns the last access time of a file |
FullName |
Returns the absolute path of a file |
LastWriteTime |
Returns the last write time of a file |
Name |
Returns the file name of the given file |
Delete () |
The method of deleting a file, make sure you use this method carefully |
The DirectoryInfo class provides methods for creating, deleting, and moving directories, and to use the various properties in table 2, we first have to create an object of the DirectoryInfo class, and then we can access its various properties.
DirectoryInfo dir1 = new DirectoryInfo (@ "f:/test");
Console.WriteLine ("Full Name is: {0}", Dir1. FullName);
Console.WriteLine ("Attributes are: {0}", Dir1. Attributes.tostring ()); |
At the same time, we can use the FileAttributes enumeration type value to get the various attributes related to the file, and the following table shows the various values in the enumerated type.
Table 3
Value |
function and use |
Archive |
Returns the archive status of a file |
Compressed |
Returns whether the file is compressed |
Directory |
Returns whether a file is a directory |
Encrypted |
Returns whether the file is encrypted |
Hidden |
Returns whether the file is hidden |
Offline |
Indicates that the file data is not available |
ReadOnly |
Indicates that the file is read-only |
System |
Indicates that the file is a system file |
file operations under the directory
Using the object of the DirectoryInfo class we can easily implement the directory and the files in the directory-related operations, if you want to obtain a directory f:/pictures all BMP files, then the following code can implement this function.
DirectoryInfo dir = new DirectoryInfo (@ "f:/ Pictures ");
fileinfo[] Bmpfiles = dir. GetFiles ("*.bmp");
Console.WriteLine ("Total number of BMP files", Bmpfiles. Length);
Foreach (FileInfo f in bmpfiles)
{
Console.WriteLine (' Name is: {0} ', f.name);
Console.WriteLine ("Length of the file is: {0}", f.length);
Console.WriteLine ("Creation time is: {0}", f.creationtime);
Console.WriteLine ("Attributes of the file are: {0}",
f.attributes.tostring ());
} |
In the code above, we first create a DirectoryInfo object and then get all the BMP-extended files under the directory F:/pictures by calling the object's GetFiles method, which returns the value of an array of fileinfo types. Each element represents a file. Finally, the program also enumerates the related properties of each BMP file.
Create subdirectories
Using the DirectoryInfo class to create subdirectories is very easy, you just call the Createsubdirectory () method, the demo code is as follows.
DirectoryInfo dir = new DirectoryInfo (@ "f:/ Pictures ");
Try
{
dir. Createsubdirectory ("Sub");
Dir. Createsubdirectory (@ "sub/mysub");
}
catch (IOException e)
{
Console.WriteLine (e.message);
} |
Use the FileInfo class to create and delete files
Through the FileInfo class, we can easily create a file, and can access the properties of the file can also open files, close the file, read and write files, and other basic operations. The following code shows how to create a text file and access the file information such as its creation time, the absolute path of the file, and the file attributes, and finally the method for deleting the file.
FileInfo fi = new FileInfo (@ "F:/myprogram.txt");
FileStream fs = fi. Create ();
Console.WriteLine ("Creation time: {0}", fi. CreationTime);
Console.WriteLine ("Full Name: {0}", fi. FullName);
Console.WriteLine ("FileAttributes: {0}", fi. Attributes.tostring ());
Console.WriteLine ("Press any key to delete the file");
Console.read ();
Fstr. Close ();
Fi. Delete (); |
Understanding the Open () method of the FileInfo class
We have to open the file before we read and write to the file, and the FileInfo class provides us with an open () method that contains two parameters for the value of the enumerated type, one for the FileMode enumeration type and the other for the FileAccess enumeration type value. By setting these two parameter values, we can control the access mode and operation permissions of the file. The following two tables show the values of the FileMode enumeration type and the FileAccess enumeration type respectively.
Table 4
Value |
function and use |
Append |
Open the file and add the data, and the FileAccess enumeration type value should be write when the method is applied. |
Create |
Creates a new file that may overwrite files that already exist. |
CreateNew |
Creates a new file and throws a IOException exception if the file already exists. |
Open |
Open a file that already exists. |
OpenOrCreate |
Opens the file and creates it if the file does not exist. |
Truncate |
Truncate a file that already exists. |
Table 5
Value |
function and use |
Read |
You can read data from a file. |
ReadWrite |
You can read data from one file and write data to the file. |
Write |
You can write data to the file. |
The following code shows how the open () method is used.
FileInfo f = new FileInfo ("F:/myfile.txt");
FileStream s = F.open (Filemode.openorwrite, FileAccess.Read); |
using StreamReader class and StreamWriter class to implement file read and write operation
Read and write to the file should be the most important file operations, System.IO namespace for us to provide a number of file reading and writing operations, where I would like to introduce the most commonly used and most basic StreamReader class and StreamWriter class. From the names of these two classes, it is not difficult to find that they are both read and write operations based on streaming.
We can get a StreamReader object through the OpenText () method of the file class, through which we can implement a read operation on a text file by using the following methods:
Console.WriteLine ("Reading the contents from the file");
StreamReader s = File.OpenText ("MyText.txt");
string read = null;
while (read = S.readline ())!= null)
{
Console.WriteLine (read);
}
S.close (); |
By invoking the CreateText () method of the FileInfo class we can get a StreamWriter object, invoke the WriteLine () of the StreamWriter class, and we can write the data to the text file in the following way:
FileInfo f = new FileInfo ("MyText.txt")
StreamWriter w = f.createtext ();
W.writeline ("This are from");
W.writeline ("Chapter 1");
W.writeline ("of C # Module");
W.write (w.newline);
W.writeline ("For your Time");
W.close (); |