两者方法类似,区别是Directory类提供了静态方法而非实例方法。另外,Directory类只提供方法,而没有提供任何特性。
一般来说,如果执行许多目录操作,则使用Directory类,实例化DirectoryInfo对象之后,该对象就具有当前操作的目录的相关信息。相反,Directory类较为简单,适用于偶然处理目录的情况。
---------------DirectoryInfo类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication32
{
classProgram
{
static void Main(string[] args)
{
string path = @"C:My Folder";
DirectoryInfo di = newDirectoryInfo(path);
try
{
if (!di.Exists)
{
di.Create();
di.CreateSubdirectory("Subdir1");
di.CreateSubdirectory("Subdir2");
}
Console.WriteLine(di.FullName);
Console.WriteLine(di.CreationTime);
//
DirectoryInfo[] subDirs = di.GetDirectories();
foreach (DirectoryInfo subDir in subDirs)
Console.WriteLine(subDir.FullName);
//
DirectoryInfo parent = di.Parent;
if (parent.Exists)
{
Console.WriteLine(parent.FullName);
}
//
DirectoryInfo newlyCreatedFolder =di.CreateSubdirectory("Subdir3");
newlyCreatedFolder.Delete();
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
------------------------Directory类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
usingSystem.IO;
namespace ConsoleApplication33
{
classProgram
{
static void Main(string[] args)
{
string path = @"C:My Folder";
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
Directory.SetCurrentDirectory(path);
Directory.CreateDirectory("Subdir1");
Directory.CreateDirectory("Subdir2");
}
Directory.SetCurrentDirectory(path);
Console.WriteLine(Directory.GetCurrentDirectory());
Console.WriteLine(Directory.GetCreationTime(path));
string[] subDirs = Directory.GetDirectories(path);
foreach (string subDir in subDirs)
Console.WriteLine(subDir);
DirectoryInfo parent = Directory.GetParent(path);
if (parent.Exists)
{
Console.WriteLine(parent.FullName);
}
Directory.CreateDirectory("Subdir3");
Directory.Delete("Subdir3");
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}