代码改变世界

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);
}
}
}
}
}