martes, 11 de febrero de 2014

Función para sacar el nombre corto de un archivo en C#.

  Buenos días hoy les traigo una función para C# muy útil para acortar los nombres de los archivos, esta muy función me sirvió para abrir archivos .DBF ya que el controlador no puede abrir archivos de más de 8 caracteres. Esta función hace uso de kernel32.dll, el resultado sería archvi~1

La función la encontré y la comparto para que sea más fácil su búsqueda.

public static string GetShortFileName(string fileDirectory, string fileNameWithExtension)
{
    StringBuilder temp = new StringBuilder(255);

    string path = System.IO.Path.Combine(fileDirectory, fileNameWithExtension);

    int n = GetShortPathName(path, temp, 255);

    if (n == 0)
        throw new NotImplementedException();

    string extension = System.IO.Path.GetExtension(path);

    return ((temp.ToString().Split('\\')).Last()).ToLower();//.Replace(extension, string.Empty);
}

[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetShortPathName(
    [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPTStr)]    
        string path,
    [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPTStr)]    
        StringBuilder shortPath,
    int shortPathLength);

Si también tienen problemas para abrir un .DBF esto podría servirles, claro partiendo de que ya tienen la conexión
string nomFile = GetShortFileName(Path.GetDirectoryName(FilePath), Path.GetFileName(FilePath));
nomFile = nomFile.Substring(0, nomFile.Length - 4);
                
OleDbDataAdapter dadp = new OleDbDataAdapter("select * from [" + nomFile + "#DBF];", con);