프로그래밍/C#
[C#] 경로 유효성 체크 - IsValidPath
큐레이트
2023. 3. 23. 16:15
경로 유효성 체크
IsValidPath
설치파일 등에서 경로 체크시에 사용된다.
/// <summary>
/// 경로가 유효한지 체크한다.
/// </summary>
/// <param name="path">경로</param>
private bool IsValidPath(string path)
{
// 경로 길이 체크
if (path.Length < 3)
return false;
// 드라이브 문자열 체크
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
if (driveCheck.IsMatch(path.Substring(0, 3)) == false)
return false;
// 경로 이름에 사용할 수 없는 문자가 있는지 체크
string invalidPathChars = new string(Path.GetInvalidPathChars());
invalidPathChars += @":/?*" + "\"";
Regex regexInvalidPath = new Regex("[" + Regex.Escape(invalidPathChars) + "]");
if (regexInvalidPath.IsMatch(path.Substring(3, path.Length - 3)))
return false;
// 실제 경로의 드라이브가 존재하는지 체크
try
{
DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
if (dir.Exists == false)
{
string drive = System.IO.Path.GetPathRoot(path);
if (Directory.Exists(drive) == false)
{
return false;
}
}
}
catch
{
return false;
}
return true;
}
반응형