C# study notes file, directory, registry

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.IOrelated 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.IO6 classes in the namespace.

  • FileSystemInfo——The base class of FileInfo and DirectoryInfo
  • File-Contains static methods for operating files
  • ③ ——Used FileInfoto represent a file and operate on it
  • ④ ——Contains Directorystatic methods for operating the directory
  • ⑤ ——Used DirectoryInfoto represent a directory and operate on it
  • ⑥ ——Used Pathto 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:
Insert picture description here
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, StreamReaderand the encoding method can be added in the package ; you can also directly generate the StreamReaderobject and specify the encoding method (such as Encoding.Default).

3.FileInfo class

FileInfoThe class is used to represent the file path. The Filedifference with the class is that all its members are non- staticspecific. Some functions can be Fileimplemented with FileInfoclasses or classes. Note: All methods in the File class require security checks. If you want to perform many operations on the same file, it FileInfowill 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 FileSystemInfoinherited from its parent class .
Insert picture description here
Insert picture description here

4.Directory class

DirectoryThe class provides static methods that can operate on directories, including operations such as creating, deleting, moving, copying, and listing directories. An Directoryobject can be used to represent a path that names an existing directory, or it can be used to create a new directory.
Insert picture description here

5.DirectoryInfo class

DirectoryInfoClasses are used to represent directories. An DirectoryInfoobject represents a path, which is either used to name an existing directory or used to create a new directory.
Insert picture description here
Insert picture description here

6.Path class

Use Pathclasses to handle the path names of files and directories in a cross-platform manner. All methods in this class are staticthe same.
Insert picture description here
Insert picture description hereInsert picture description here

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类

FileSystemWatcherIs 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 FileSystemWatcherobject 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

FileSystemWatcherThe Pathattribute of indicates the directory to be monitored.
FilterThe 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 ( ""). IncludeSubdirectoriesThe 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.NotifyFilterattribute to NotifyFiltersone of the values ​​or a combination of them.
Insert picture description here

4. Event

When files and directories are changed, they FileSystemWatchercan respond by generating an event. At this time, the client code needs to execute some event handler code.
Insert picture description here
Common file system operations may cause multiple events. For example, when a file from one directory to another directory, could trigger several Changedwell as some Createdand Deletedevents. 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 FileSystemWatcheradditional file system events to be detected.
The agent used for event processing is FileSystemEventHandlerand RenamedEventHandler. In addition object senderto the parameters in the event processing function , there is another FileSystemEventArgsobject, which contains event-related information. The most useful properties of FieSystemEventArgs are as follows:

  • ① ——Contains FullPaththe 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 RenamedEventArgsmost commonly used attributes are OldFullPahand FullPah, respectively, the original name and the name later.
When the setup program EnableRaisingEventsproperty 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, NotifyFilterand IncludeSubdirectoriesproperty, 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:
Insert picture description here
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.

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/114552709