Last active
August 29, 2015 14:06
-
-
Save alxsimo/a8c7174dbe287bd37d00 to your computer and use it in GitHub Desktop.
[C#] Fuzzy search name file in folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using DuoVia.FuzzyStrings; | |
/// <summary> | |
/// Busca el fichero con el nombre que mas se parece en la ruta elegida. | |
/// Si no encuentra el fichero o carpeta devuelve Excepciones. | |
/// Depende de DuoVia.FuzzyStrings | |
/// </summary> | |
/// <param name="path">Ruta donde buscar</param> | |
/// <param name="filename">Nombre del fichero a buscar</param> | |
/// <returns>Coincidencia mas exacta del fichero encontrado</returns> | |
public static string FuzzySearchFileInFolder(string path, string filename, bool absolutePath = true) | |
{ | |
string[] filesInFolder; | |
int[] points; | |
string fileEncontrado; | |
string fileEncontradoAbs; | |
if (Directory.Exists(path)) | |
{ | |
filesInFolder = new List<string>(Directory.EnumerateFiles(path)).ToArray(); | |
if (filesInFolder.Length > 0) | |
{ | |
points = new int[filesInFolder.Length]; | |
// Recorre directorio y guarda puntos | |
for (int i = 0; i < filesInFolder.Length; i++) | |
{ | |
points[i] = filesInFolder[i].LevenshteinDistance(filename); | |
} | |
int minValue = points.Min(); | |
int minIndex = points.ToList().IndexOf(minValue); | |
fileEncontrado = filesInFolder[minIndex]; | |
fileEncontradoAbs = Path.Combine(path, fileEncontrado); | |
} | |
else | |
{ | |
throw new FileNotFoundException(String.Format("Fichero {0} no encontrado o directorio vacio en {1}", filename, path)); | |
} | |
} | |
else | |
{ | |
throw new DirectoryNotFoundException(String.Format("Directorio {0} no encontrado ", path)); | |
} | |
if (absolutePath) | |
return fileEncontradoAbs; | |
else | |
return fileEncontrado; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment