방법: 파일, 폴더 및 드라이브에 대한 정보 가져오기(C# 프로그래밍 가이드)
.NET Framework에서 다음과 같은 클래스를 사용하여 파일 시스템 정보에 액세스할 수 있습니다.
FileInfo 및 DirectoryInfo 클래스는 파일 또는 디렉터리를 나타내며 NTFS 파일 시스템이 지원하는 많은 파일 특성을 노출하는 속성을 포함합니다. 또한 파일 및 폴더 열기, 닫기, 이동, 삭제를 위한 메서드도 포함합니다. 다음과 같이 생성자에 파일, 폴더 또는 드라이브 이름을 나타내는 문자열을 전달하여 이러한 클래스의 인스턴스를 만들 수 있습니다.
System.IO.DriveInfo di = new System.IO.DriveInfo(@"C:\");
DirectoryInfo.GetDirectories, DirectoryInfo.GetFiles 및 DriveInfo.RootDirectory를 호출하여 파일, 폴더 또는 드라이브 이름을 얻을 수도 있습니다.
Directory 및 File 클래스는 디렉터리 및 파일에 대한 정보를 검색하는 정적 메서드를 제공합니다.
예제
다음 예제에서는 파일 및 폴더 정보에 액세스하는 여러 가지 방법을 보여 줍니다.
class FileSysInfo
{
static void Main()
{
// You can also use System.Environment.GetLogicalDrives to
// obtain names of all logical drives on the computer.
System.IO.DriveInfo di = new System.IO.DriveInfo(@"C:\");
Console.WriteLine(di.TotalFreeSpace);
Console.WriteLine(di.VolumeLabel);
// Get the root directory and print out some information about it.
System.IO.DirectoryInfo dirInfo = di.RootDirectory;
Console.WriteLine(dirInfo.Attributes.ToString());
// Get the files in the directory and print out some information about them.
System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");
foreach (System.IO.FileInfo fi in fileNames)
{
Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length);
}
// Get the subdirectories directly that is under the root.
// See "How to: Iterate Through a Directory Tree" for an example of how to
// iterate through an entire tree.
System.IO.DirectoryInfo[] dirInfos = dirInfo.GetDirectories("*.*");
foreach (System.IO.DirectoryInfo d in dirInfos)
{
Console.WriteLine(d.Name);
}
// The Directory and File classes provide several static methods
// for accessing files and directories.
// Get the current application directory.
string currentDirName = System.IO.Directory.GetCurrentDirectory();
Console.WriteLine(currentDirName);
// Get an array of file names as strings rather than FileInfo objects.
// Use this method when storage space is an issue, and when you might
// hold on to the file name reference for a while before you try to access
// the file.
string[] files = System.IO.Directory.GetFiles(currentDirName, "*.txt");
foreach (string s in files)
{
// Create the FileInfo object only when needed to ensure
// the information is as current as possible.
System.IO.FileInfo fi = null;
try
{
fi = new System.IO.FileInfo(s);
}
catch (System.IO.FileNotFoundException e)
{
// To inform the user and continue is
// sufficient for this demonstration.
// Your application may require different behavior.
Console.WriteLine(e.Message);
continue;
}
Console.WriteLine("{0} : {1}",fi.Name, fi.Directory);
}
// Change the directory. In this case, first check to see
// whether it already exists, and create it if it does not.
// If this is not appropriate for your application, you can
// handle the System.IO.IOException that will be raised if the
// directory cannot be found.
if (!System.IO.Directory.Exists(@"C:\Users\Public\TestFolder\"))
{
System.IO.Directory.CreateDirectory(@"C:\Users\Public\TestFolder\");
}
System.IO.Directory.SetCurrentDirectory(@"C:\Users\Public\TestFolder\");
currentDirName = System.IO.Directory.GetCurrentDirectory();
Console.WriteLine(currentDirName);
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
강력한 프로그래밍
사용자가 지정한 경로 문자열을 처리할 때 다음과 같은 예외 상황을 처리해야 합니다.
파일 이름의 형식이 잘못된 경우. 예를 들어 파일 이름에 잘못된 문자가 들어 있거나 공백이 있을 수 있습니다.
경로 이름이 null인 경우
파일 이름이 시스템에 정의된 최대 길이보다 긴 경우
파일 이름에 콜론(:)이 있는 경우
지정된 파일을 읽을 수 있는 충분한 권한이 응용 프로그램에 없으면 경로의 존재 여부와 상관없이 Exists 메서드에서 false를 반환합니다. 이때 메서드는 예외를 throw하지 않습니다.