경로가 유효한지 확인
나는 단지 궁금합니다. 주어진 경로가 유효한지 확인하는 방법을 찾고 있습니다. (참고 : 파일이 존재하는지 확인하고 싶지! 경로의 유효성 만 증명하고 싶습니다 .
Net API에서 아무것도 제거하지 않습니다. Windows가 지원하는 많은 형식과 위치로 인해 MS 파일을 사용하고 싶습니다.
함수는 항상 확인할 수 있기 때문에 :
- 상대 경로 (./)
- 절대 경로 (c : \ tmp)
- UNC 경로 (\ some-pc \ c $)
- 전체 경로 1024 문자와 같은 NTFS 제한-경로 초과하지 않는 많은 내부 Windows 기능에서 파일에 액세스 할 수 없습니다. 탐색기로 이름을 바꾸는 것은 여전히 작동합니다.
- 볼륨 GUID 경로 : "\? \ 볼륨 {GUID} \ somefile.foo
누구든지 이와 같은 기능이 있습니까?
시도해 시도 :Uri.IsWellFormedUriString()
이스케이프는 신뢰할 수 없습니다.
http://www.example.com/path???/file name
는 암시 적 파일 Uri를 절대 Uri입니다.
c:\\directory\filename
앞서가는 경로 슬래시가없는 절대 URI입니다.
file://c:/directory/filename
슬래시로 취급되지 않는 백 슬래시를 포함합니다.
http:\\host/path/file
": //"를 포함하지 않습니다.
www.example.com/path/file
Uri.Scheme의 구문 분석기는 일반적으로 형식이 잘못 나타납니다.
The example depends on the scheme of the URI.
또는 사용 에서는에서는 FileInfo를 에 제안 에서 C #을 확인 파일 이름이 가능하게 (존재하지 않는 것이) 유효합니다 .
private bool IsValidPath(string path)
{
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
strTheseAreInvalidFileNameChars += @":/?*" + "\"";
Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
return false;
DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
if (!dir.Exists)
dir.Create();
return true;
}
아래 코드에 문제가 없습니다. (상대 경로는 '/'또는 '\'로 시작해야합니다.)
private bool IsValidPath(string path, bool allowRelativePaths = false)
{
bool isValid = true;
try
{
string fullPath = Path.GetFullPath(path);
if (allowRelativePaths)
{
isValid = Path.IsPathRooted(path);
}
else
{
string root = Path.GetPathRoot(path);
isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
}
}
catch(Exception ex)
{
isValid = false;
}
return isValid;
}
예를 들어 다음은 거짓을 반환합니다.
IsValidPath("C:/abc*d");
IsValidPath("C:/abc?d");
IsValidPath("C:/abc\"d");
IsValidPath("C:/abc<d");
IsValidPath("C:/abc>d");
IsValidPath("C:/abc|d");
IsValidPath("C:/abc:d");
IsValidPath("");
IsValidPath("./abc");
IsValidPath("./abc", true);
IsValidPath("/abc");
IsValidPath("abc");
IsValidPath("abc", true);
그리고 이것은 사실을 반환합니다.
IsValidPath(@"C:\\abc");
IsValidPath(@"F:\FILES\");
IsValidPath(@"C:\\abc.docx\\defg.docx");
IsValidPath(@"C:/abc/defg");
IsValidPath(@"C:\\\//\/\\/\\\/abc/\/\/\/\///\\\//\defg");
IsValidPath(@"C:/abc/def~`!@#$%^&()_-+={[}];',.g");
IsValidPath(@"C:\\\\\abc////////defg");
IsValidPath(@"/abc", true);
IsValidPath(@"\abc", true);
내가 가장 가까운 것은 그것을 만들려고 시도하고 성공하는지 확인하는 것입니다.
이 코드를 시도해 볼 수 있습니다.
try
{
Path.GetDirectoryName(myPath);
}
catch
{
// Path is not valid
}
모든 경우를 다룰 수 있을지 모르겠습니다 ...
잘못된 문자를 가져 와서 System.IO.Path.GetInvalidPathChars();
문자열 (디렉터리 경로)에 해당 문자가 포함 되어 있는지 확인하십시오.
여기에는 좋은 솔루션이 많이 있지만 경로가 기존 드라이브에 뿌리를두고 있는지 확인하는 방법은 다음과 같습니다.
private bool IsValidPath(string path)
{
// Check if the path is rooted in a driver
if (path.Length < 3) return false;
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
// Check if such driver exists
IEnumerable<string> allMachineDrivers = DriveInfo.GetDrives().Select(drive => drive.Name);
if (!allMachineDrivers.Contains(path.Substring(0, 3))) return false;
// Check if the rest of the path is valid
string InvalidFileNameChars = new string(Path.GetInvalidPathChars());
InvalidFileNameChars += @":/?*" + "\"";
Regex containsABadCharacter = new Regex("[" + Regex.Escape(InvalidFileNameChars) + "]");
if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
return false;
if (path[path.Length - 1] == '.') return false;
return true;
}
이 솔루션은 상대 경로를 고려 하지 않습니다 .
private bool IsValidPath(string path)
{
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
if (string.IsNullOrWhiteSpace(path) || path.Length < 3)
{
return false;
}
if (!driveCheck.IsMatch(path.Substring(0, 3)))
{
return false;
}
var x1 = (path.Substring(3, path.Length - 3));
string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
strTheseAreInvalidFileNameChars += @":?*";
Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
{
return false;
}
var driveLetterWithColonAndSlash = Path.GetPathRoot(path);
if (!DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash))
{
return false;
}
return true;
}
Path.IsPathRooted ()를 Path.GetInvalidFileNameChars ()와 함께 사용하여 경로가 중간 정도인지 확인할 수 있습니다.
참고 URL : https://stackoverflow.com/questions/6198392/check-whether-a-path-is-valid
'IT' 카테고리의 다른 글
HTML5 데이터 속성을 사용하는 CSS 값 (0) | 2020.08.22 |
---|---|
C ++ 소멸자는 언제 호출? (0) | 2020.08.22 |
npm 경고 ……의 피어가 필요하지만 설치되어 있지 않습니다. (0) | 2020.08.22 |
기존 Visual Studio 프로젝트에서 Visual Studio 프로젝트 유형을 어떻게 지정합니까? (0) | 2020.08.22 |
제네릭 형식 매개 변수에 대한 정적 메서드 호출 (0) | 2020.08.22 |