C# - 폴더 경로 문자열에서 "..", "." 표기를 고려한 최종 문자열을 얻는 방법
개인적으로 System.IO.Path.Combine 메서드의 사용을 꽤나 좋아합니다.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
string etcPath = Path.Combine(systemPath, "drivers", "etc");
Console.WriteLine(etcPath); // C:\Windows\system32\drivers\etc
Console.WriteLine(Directory.Exists(etcPath)); // True
}
}
'\' 문자의 사용을 귀찮게 고려할 필요없이, 그냥 이름만 주면 알아서 척척 경로를 이어서 주기 때문인데요.
그런데, 가끔은 Path.Combine으로 부모 디렉토리로 이동하는 등의 경로 구성을 할 때 불편한 점이 있습니다.
// etcPath == C:\Windows\system32\drivers\etc
string winPath = System.IO.Path.Combine(etcPath, "..", "..", "..");
Console.WriteLine(winPath); // C:\Windows\system32\drivers\etc\..\..\..
보시는 것처럼, 출력 결과가 끝에 ".." 경로가 붙은 체로 반환되므로 별로 깔끔하지 않게 됩니다. 이럴 때 경로를 단일하게 구성하고 싶다면 DirectoryInfo 클래스의 도움을 받으면 됩니다.
DirectoryInfo dirInfo = new DirectoryInfo(winPath); // winPath == C:\Windows\system32\drivers\etc\..\..\..
Console.WriteLine(dirInfo.FullName); // C:\Windows
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]