2011-06-01 106 views
82

我只是想知道:我正在尋找一種方法來驗證給定的路徑是否有效。 (注意:我不想檢查文件是否存在!我只想證明路徑的有效性 - 所以如果文件可能存在於該位置)檢查路徑是否有效

問題是,我在.Net API中找不到任何東西。 由於Windows支持多種格式和位置,我寧願使用MS-native。

由於函數應該能夠覈對:

  • 相對路徑(./)
  • 的絕對路徑(C:\ TMP)
  • UNC-Pathes(\一些-PC \ c $)
  • NTFS限制像完整路徑1024個字符 - 如果我沒有誤超過路徑將使許多 內部Windows功能無法訪問文件。用資源管理器重新命名它仍然有效
  • 卷GUID路徑:??「\ \卷{GUID} \ somefile.foo

有沒有人有這樣的功能

+0

可能重複Windows?](http://stackoverflow.com/questions/62771/how-check-if-given-string-is-legal-allowed-file-name-under-windows) – nawfal 2013-06-05 11:43:40

回答

2
+3

「[...]不想要檢查一個文件是否存在!「 – Stefan 2011-06-01 08:44:29

+3

該測試目錄存在,而不是它是一個有效的路徑(其中可能存在或創建,給予適當的權限) – Martijn 2011-06-01 08:45:09

+3

@Jason - 它不檢查文件,只檢查包含的文件夾。 – markpsmith 2011-06-01 08:46:34

51

嘗試Uri.IsWellFormedUriString()

  • 該字符串未正確轉義。

    http://www.example.com/path???/file name 
    
  • 的字符串是絕對URI表示一個隱含的文件URI。

    c:\\directory\filename 
    
  • 該字符串是絕對URI,在路徑前缺少斜槓。

    file://c:/directory/filename 
    
  • 該字符串包含未轉義的反斜槓,即使它們被視爲正斜槓。

    http:\\host/path/file 
    
  • 該字符串表示層次絕對的Uri並且不包含「://」。

    www.example.com/path/file 
    
  • Uri.Scheme的解析器指示原始字符串格式不正確。

    The example depends on the scheme of the URI. 
    
+0

這聽起來很有希望......我仔細看看它!在評估了方法是否符合我的目的後,我會放下一行。由於abatishchev – Corelgott 2011-06-01 12:45:01

+6

這將返回false爲'@「foo \ bar \ baz」',這是一個完全有效的相對路徑... – 2012-10-18 08:26:28

+4

托馬斯:你指定了什麼UriKind?您可以使用絕對,相對或絕對或相對。 – danglund 2013-02-09 10:38:18

3

我來最接近的是,試圖創建它,看它是否成功。

1

System.IO.Path.GetInvalidPathChars();獲取無效字符,並檢查您的字符串(目錄路徑)是否包含這些字符。

+3

這不完全有效。 「C:\ new.folder」在「C:\ newfolder」中有效。不是。 ''是路徑/文件名的有效字符,但不在uri的末尾。 – claudekennilol 2013-03-07 16:13:01

+4

另外'C:我的\文件夾'是一個有效的... – Nickon 2013-04-16 13:17:21

-4

您可以嘗試將Path.IsPathRooted()與Path.GetInvalidFileNameChars()組合使用,以確保路徑是中途還好。

6
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; 
} 
3

你可以試試這個代碼:

try 
{ 
    Path.GetDirectoryName(myPath); 
} 
catch 
{ 
    // Path is not valid 
} 

我不知道它涵蓋了所有的情況下...

-1
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; 
} 
+0

這工作沒有try-catch塊。 – 2016-10-31 12:54:37

+0

x1的目的是什麼? – JayJay 2017-09-29 20:04:45

0

我還沒有與任何代碼的問題下面。 (相對路徑必須以'/'或'\'開頭)。

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; 
} 

例如,這些將返回false:

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); 

而這些將返回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~`[email protected]#$%^&()_-+={[}];',.g"); 
IsValidPath(@"C:\\\\\abc////////defg"); 
IsValidPath(@"/abc", true); 
IsValidPath(@"\abc", true); 
的[如何檢查,如果給定的字符串是合法的(允許)下的文件名