C# 文件路径波浪线(~)转换为实际名称&Dos8.3路径规则转换
C# 读取文件或文件夹的时候,路径有时候会变成带有波浪线(~)的形式,这是DOS 8.3文件名规则,感兴趣的小伙伴可以搜搜看。
遇到这种情况,想要转换成实际路径,需要调用Win32 API,代码如下:
其中GetShortPathName方法,是将路径全名转换为DOS 8.3规则,GetLongPathName方法,是将DOS8.3规则的形式转换为全名称路径
调用方法之后,如果没有获取到自己期望的结果,可以再调用一下int errorCode = Marshal.GetLastWin32Error();来检查错误情况。错误代码对应值参考微软官方链接
如有疑问,欢迎评论区留言
/// <summary> /// Dos8.3名称规则转换 /// </summary> public class Dos8_3Helper { /// <summary> /// /// </summary> /// <param name="longPath"></param> /// <param name="shortPath"></param> /// <param name="shortPathLength"></param> /// <returns></returns> [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern int GetShortPathName(string longPath, StringBuilder shortPath, int shortPathLength); /// <summary> /// /// </summary> /// <param name="sourceFilePath"></param> /// <param name="pathResult"></param> public static bool AmanShortPathName(string sourceFilePath,out string pathResult) { StringBuilder shortPathBuffer = new StringBuilder(1000); int result = GetShortPathName(sourceFilePath, shortPathBuffer, shortPathBuffer.Capacity); if (result != 0) { pathResult = shortPathBuffer.ToString(); return true; } else { pathResult = string.Empty; return false; } } /// <summary> /// /// </summary> /// <param name="shortPath"></param> /// <param name="longPath"></param> /// <param name="longPathLength"></param> /// <returns></returns> [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern int GetLongPathName(string shortPath, StringBuilder longPath, int longPathLength); /// <summary> /// /// </summary> /// <param name="sourceFilePath"></param> /// <param name="pathResult"></param> public static bool AmanLongPathName(string sourceFilePath,out string pathResult) { StringBuilder longPathBuffer = new StringBuilder(1000); int result = GetLongPathName(sourceFilePath, longPathBuffer, longPathBuffer.Capacity); if (result != 0) { pathResult = longPathBuffer.ToString(); return true; } else { pathResult = string.Empty; return false; } } }