C#文件系统复习
2011-07-19 10:02 RyanXiang 阅读(415) 评论(1) 编辑 收藏 举报1、获取驱动器名称
using System;
namespace TestFile
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine();
String[] drives = Environment.GetLogicalDrives();
foreach(string drive in drives)
{
Console.WriteLine(drive);
}
Console.WriteLine("GetLogicalDrives: {0}", String.Join(", ", drives));
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
2、System.IO.DriverInfo相关属性
using System;
namespace TestFile
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine();
//获取驱动器名称
String[] drives = Environment.GetLogicalDrives();
//遍历驱动器名称
foreach(string dr in drives)
{
//获取驱动器相关信息
System.IO.DriveInfo driver = new System.IO.DriveInfo(dr);
Console.WriteLine("驱动器可用空间: "+driver.AvailableFreeSpace);
//NTFS or FAT
Console.WriteLine("驱动器格式化类型: "+driver.DriveFormat);
//CDRom、Fixed、Unknown、Network、NoRootDirectory、Ram、Removable 或 Unknown
Console.WriteLine("驱动器类型: "+driver.DriveType);
//如果驱动器已准备好,则为 true;如果驱动器未准备好,则为 false。
Console.WriteLine("驱动器是否准备好: "+driver.IsReady);
Console.WriteLine("驱动器名称: "+driver.Name);
Console.WriteLine("驱动器根目录: "+driver.RootDirectory);
Console.WriteLine("========================================================");
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
3、递归遍历指定文件夹中的目录
using System;
using System.IO;
namespace DirectoryTest
{
public class RecursiveFileSearch
{
static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection();
static void Main()
{
DirectoryInfo rootDir = new DirectoryInfo("C:\\Oracle\\ora90");
WalkDirectoryTree(rootDir);
Console.WriteLine("Files with restricted access:");
foreach (string s in log)
{
Console.WriteLine(s);
}
Console.WriteLine("Press any key");
Console.ReadKey();
}
/// <summary>
/// 循环遍历指定目录
/// </summary>
/// <param name="root"></param>
static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
System.IO.FileInfo[] files = null;
System.IO.DirectoryInfo[] subDirs = null;
//1、获取root下的所有文件(包括文件夹)
try
{
files = root.GetFiles("*.*");
}
//2、权限不够引发异常
catch (UnauthorizedAccessException e)
{
//提权或记录日志
log.Add(e.Message);
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}
if (files != null)
{
foreach (System.IO.FileInfo fi in files)
{
Console.WriteLine(fi.FullName);
}
// 获取所有子目录
subDirs = root.GetDirectories();
foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
// 递归调用
WalkDirectoryTree(dirInfo);
}
}
}
}
}
作者:塞北隐士
出处:http://www.cnblogs.com/xiangyun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
反馈文章质量,你可以通过快速通道评论: