Me pregunto: estoy buscando una forma de validar si un camino determinado es válido. (Nota: ¡No quiero verificar si un archivo existe! Solo quiero probar la validez de la ruta, por lo tanto, si es posible que exista un archivo en la ubicación) .
El problema es que no puedo encontrar nada en la API de .Net. Debido a los muchos formatos y ubicaciones que admite Windows, prefiero usar algo nativo de MS.
Dado que la función debería poder verificar contra:
- Rutas relativas (./)
- Rutas absolutas (c: \ tmp)
- UNC-Pathes (\ some-pc \ c $)
- Limitaciones de NTFS como la ruta completa 1024 caracteres: si no me equivoco al exceder la ruta, se hará que un archivo sea inaccesible para muchas funciones internas de Windows. Renombrarlo con Explorer todavía funciona
- Rutas de GUID de volumen: “\? \ Volume {GUID} \ somefile.foo
¿Alguien tiene una función como esta?
Pruebe Uri.IsWellFormedUriString()
:
La cadena no se escapó correctamente.
http://www.example.com/path???/file name
La cadena es un Uri absoluto que representa un archivo implícito Uri.
c:\\directory\filename
La cadena es un URI absoluto que falta una barra antes de la ruta.
file://c:/directory/filename
La cadena contiene barras invertidas no guardadas incluso si se tratan como barras diagonales.
http:\\host/path/file
La cadena representa un Uri absoluto jerárquico y no contiene “: //”.
www.example.com/path/file
El analizador del Uri.Scheme indica que la cadena original no estaba bien formada.
The example depends on the scheme of the URI.
O use el FileInfo como se sugiere en In C Verifique que el nombre del archivo sea posiblemente válido (no que exista) .
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; }
No he tenido ningún problema con el código a continuación. (Las rutas relativas deben comenzar con ‘/’ o ‘\’).
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; }
Por ejemplo, estos devolverían falso
IsValidPath("C:/abc*d"); IsValidPath("C:/abc?d"); IsValidPath("C:/abc\"d"); IsValidPath("C:/abcd"); IsValidPath("C:/abc|d"); IsValidPath("C:/abc:d"); IsValidPath(""); IsValidPath("./abc"); IsValidPath("./abc", true); IsValidPath("/abc"); IsValidPath("abc"); IsValidPath("abc", true);
Y estos regresarían verdaderos:
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);
Puedes probar este código:
try { Path.GetDirectoryName(myPath); } catch { // Path is not valid }
No estoy seguro de que cubra todos los casos …
Lo más cerca que he llegado es tratando de crearlo, y ver si tiene éxito.
Directory.Exists?
Obtenga los caracteres no válidos de System.IO.Path.GetInvalidPathChars();
y compruebe si su cadena (ruta del directorio) contiene esos o no.
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; }
Podría intentar usar Path.IsPathRooted () en combinación con Path.GetInvalidFileNameChars () para asegurarse de que la ruta esté a medio camino.