A file is a collection of information stored on a disk; a directory, a folder, is a way of organizing multiple files; a registry is where various configuration information is stored in the operating system Land (database).
File and directory management
C# supports file management and directory management, which are implemented by System.IO
related classes in the namespace. These classes are not subclasses of Stream or TextReader, because they are not responsible for the input/output of content, but are used to manage disk files and directories.
Files and directories are represented by System.IO
6 classes in the namespace.
- ①
FileSystemInfo
——The base class of FileInfo and DirectoryInfo - ②
File
-Contains static methods for operating files - ③ ——Used
FileInfo
to represent a file and operate on it - ④ ——Contains
Directory
static methods for operating the directory - ⑤ ——Used
DirectoryInfo
to represent a directory and operate on it - ⑥ ——Used
Path
to operate on path information
1.FileSystemInfo类
FieSystemlnfo class is the base class of Filelnfo and Directorylnfo, used to operate files and directories. This class provides many methods and attributes commonly used in files and directories.
2.File class
The following table is the method provided in the File class:
Example, directly use the File class to read the content, and display each line:
using System;
using System.IO;
class FileOpenText
{
static void Main(){
StreamReader sr = File.OpenText(".\\FileOpenText.cs");
string contents = sr.ReadToEnd();
sr.Close();
string[] lines = contents.Split(new char[] {
'\n' });
for(int i = 0; i < lines.Length; i++)
Console.WriteLine(i + ":\t" + lines[i]);
}
}
Although File.OpenText()
it is very convenient, it cannot be used directly for some files with different encoding methods (such as Chinese character GB codes) File.OpenText()
. It can be used FileStream
, StreamReader
and the encoding method can be added in the package ; you can also directly generate the StreamReader
object and specify the encoding method (such as Encoding.Default
).
3.FileInfo class
FileInfo
The class is used to represent the file path. The File
difference with the class is that all its members are non- static
specific. Some functions can be File
implemented with FileInfo
classes or classes. Note: All methods in the File class require security checks. If you want to perform many operations on the same file, it FileInfo
will be more efficient to create an object for processing, because the FileInfo object does not require security checks every time it is called.
The methods and properties in the FileInfo class are FileSystemInfo
inherited from its parent class .
4.Directory class
Directory
The class provides static methods that can operate on directories, including operations such as creating, deleting, moving, copying, and listing directories. An Directory
object can be used to represent a path that names an existing directory, or it can be used to create a new directory.
5.DirectoryInfo class
DirectoryInfo
Classes are used to represent directories. An DirectoryInfo
object represents a path, which is either used to name an existing directory or used to create a new directory.
6.Path class
Use Path
classes to handle the path names of files and directories in a cross-platform manner. All methods in this class are static
the same.
For example, ListAlFiles.cs recursively lists all files in a directory.
using System;
using System.IO;
class ListAllFiles
{
public static void Main(){
ListFiles(new DirectoryInfo(@"C:\Users\Frenkie\Desktop"));
}
public static void ListFiles(FileSystemInfo info) {
if (!info.Exists) return;
DirectoryInfo dir = info as DirectoryInfo;
if (dir == null) return; // 不是目录
FileSystemInfo[] files = dir.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++) {
FileInfo file = files[i] as FileInfo;
if (file != null) // 是文件
Console.WriteLine(file.FullName + "\t" + file.Length);
else // 是目录
ListFiles(files[i]);// 对于子目录, 进行递归调用
}
}
}
Monitor changes to files and directories
1.FileSystemWatcher类
FileSystemWatcher
Is a very useful class, it can monitor the changes of files and subdirectories in the specified directory. The detected directory can be on the local machine, it can be a network drive, or even a directory on a remote machine.
An FileSystemWatcher
object can be created in the program to monitor a specified directory. When the files or subdirectories in the monitored directory are created, modified, or deleted, the object can generate events as a response.
2.Path and Filter attributes
FileSystemWatcher
The Path
attribute of indicates the directory to be monitored.
Filter
The attribute is used to specify to monitor certain files in the directory. For example, if you want to monitor changes in text files, you should set the Filter property to "*.txt"
. If only a certain file is monitored, its file name is used. To monitor changes in all files, the Filter property should be set to an empty string ( ""
). IncludeSubdirectories
The attribute is used to indicate whether to include subdirectories.
3.NotifyFilters property
Several changes in directories or files can be monitored. For example, you can monitor the modification of the Attributes, LastWrite date and time, or Size of a file or directory. This is achieved by setting the FileSystemWatcher.NotifyFilter
attribute to NotifyFilters
one of the values or a combination of them.
4. Event
When files and directories are changed, they FileSystemWatcher
can respond by generating an event. At this time, the client code needs to execute some event handler code.
Common file system operations may cause multiple events. For example, when a file from one directory to another directory, could trigger several Changed
well as some Created
and Deleted
events. Moving a file is a complex operation that includes multiple simple operations, so multiple events are triggered. Similarly, some applications (such as anti-virus software) may cause FileSystemWatcher
additional file system events to be detected.
The agent used for event processing is FileSystemEventHandler
and RenamedEventHandler
. In addition object sender
to the parameters in the event processing function , there is another FileSystemEventArgs
object, which contains event-related information. The most useful properties of FieSystemEventArgs are as follows:
- ① ——Contains
FullPath
the full path of the file or directory that caused the event - ②
Name
——Only include the name of the file or directory - ③
ChangeType
——Inform the type of change
The RenamedEventArgs
most commonly used attributes are OldFullPah
and FullPah
, respectively, the original name and the name later.
When the setup program EnableRaisingEvents
property true
, it will start monitoring.
It should be noted that too many and too fast events may cause the system to require more buffers and cause a decrease in system efficiency. Therefore, rational use Filter
, NotifyFilter
and IncludeSubdirectories
property, so that you can filter out unwanted change notifications.
For example, Watcher. cs uses FileSystemWatcher to monitor file changes.
using System;
using System.IO;
class Watcher
{
public static void TestMain() {
const string path = @"E:\Visual Studio 2019\C#\Mooc学习\ConsoleApp18流、文件IO\bin\Debug";
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.Filter = "*.txt";
watcher.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.LastWrite | NotifyFilters.FileName |
NotifyFilters.DirectoryName;
// 事件处理函数
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// 开始监视
watcher.EnableRaisingEvents = true;
// 等待用户输入q才结束程序
Console.WriteLine("Press'q' to quit the sample.");
while (Console.Read() != 'q') {
}
}
// 事件处理函数
private static void OnChanged(object sender, FileSystemEventArgs e) {
// 显示哪些文件做了何种修改
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object sender, RenamedEventArgs e) {
// 显示被更改的文件名
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
}
Registry
For example, RegistryDemo.cs gets and sets the registry.
using Microsoft.Win32;
using System;
class RegistryDemo
{
public static void TestMain() {
// 获取信息
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main");
string page = key.GetValue("Start Page") as string;
Console.WriteLine("浏览器的起始页是" + page);
// 设置信息
RegistryKey test = Registry.CurrentUser.CreateSubKey("MyTest");
using (RegistryKey mySetting = test.CreateSubKey("MySetting")) {
mySetting.SetValue("ID", 123);
mySetting.SetValue("Language", "Chinese");
mySetting.SetValue("WindowSize", "Max");
mySetting.SetValue("LastLogin", DateTime.Now.ToString());
}
// 查询信息
RegistryKey setting = Registry.CurrentUser.OpenSubKey(@"MyTest\MySetting");
foreach (string name in setting.GetValueNames())
Console.WriteLine(name + ":" + setting.GetValue(name));
}
}
Operation result:
In actual work, some setting items in the program can be saved to the registry, and these registration items will be read from the registry the next time it is run.
Note: Operating the registry may cause system failures. If you are not familiar with the Windows registry, try not to manipulate the registry at will. In addition, some registry entries require specific permissions to be modified.