首页 / 网页编程 / ASP.NET / .Net笔记:System.IO之windows文件操作的深入分析
在.Net中处理系统文件相关的几个类分别是File、Directory、FileInfo、DirectoryInfo、DriveInfo、FileSystemWatcher。本文介绍下这几个类的用法。 1.File类提供静态方法用来创建、移动、复制、删除文件的操作,并可以打开文件流 2.Directory类提供静态方法用来创建、移动、复制、删除目录的操作 3.FileInfo类用类实例实现创建、复制、移动、删除文件的操作 4.DirectoryInfo提供创建、移动、复制、删除目录的操作,并可以枚举子目录 5.DriveInfo可以获得windows操作系统中的磁盘信息 6.FileSystemWatcher用来监视文件或目录变化,并引发事件 7.Path类提供文件名目录名操作的静态方法 File、FileInfo、Directory、DirectoryInfo这几个类的使用方法都非常简单就不做赘述了。 1.如何使用DriveInfo获得windows系统磁盘信息 不允许在程序中自己构造DriveInfo的实例,可以通过DriveInfo的静态方法GetDrives()获得windows系统中所有的磁盘,包括硬盘,cd以及u盘;注意在访问磁盘属性时需要先判断其IsReady属性是否为true,IsReady为false时访问磁盘的一些属性时会抛出异常。如下实例代码: 复制代码 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO;
namespace aboutio { class Program { static void Main(string[] args) { DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives) { if(drive.IsReady) Console.WriteLine("类型:{0} 卷标:{1} 名称:{2} 总空间:{3} 剩余空间:{4}",drive.DriveType, drive.VolumeLabel,drive.Name,drive.TotalSize,drive.TotalFreeSpace); else Console.WriteLine("类型:{0} is not ready",drive.DriveType); }
Console.ReadLine(); } } }
2. 使用FileSystemWatcher监视目录 FileSystemWatcher用来监视目录或者文件的修改,创建,删除,要使FileSystemWatcher开始监视必须设置其EnableRaisingEvents属性为true,如下示例: 复制代码 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading;
namespace UseFileSystemWatcher { class Program { static void Main(string[] args) { //声明要监视的目录 string watchPath = "D:\watch"; FileSystemWatcher watcher = new FileSystemWatcher(watchPath, "*.*"); //添加文件变化处理事件 watcher.Changed += new FileSystemEventHandler(Watcher_Changed); //添加文件创建处理事件 watcher.Created += new FileSystemEventHandler(Watcher_Created); //添加文件删除处理事件 watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted); //添加错误处理 watcher.Error += new ErrorEventHandler(Watcher_Error); //启动监视 watcher.EnableRaisingEvents = true; Thread.Sleep(1000 * 60); Console.WriteLine("press any key to exit.."); Console.Read(); }