standard way to convert to short path in .net

前端 未结 3 1827
眼角桃花
眼角桃花 2021-01-18 04:41

looking for the standard bug-proofed way to convert \"long names\" such as \"C:\\Documents and settings\" to their equivalent \"short names\" \"C:\\DOCUME~1\"

I need

3条回答
  •  生来不讨喜
    2021-01-18 05:39

    If you are prepared to start calling out to Windows API functions, then GetShortPathName() and GetLongPathName() provide this functionality.

    See http://csharparticles.blogspot.com/2005/07/long-and-short-file-name-conversion-in.html

        const int MAX_PATH = 255;
    
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern int GetShortPathName(
            [MarshalAs(UnmanagedType.LPTStr)]
             string path,
            [MarshalAs(UnmanagedType.LPTStr)]
             StringBuilder shortPath,
            int shortPathLength
            );
    
        private static string GetShortPath(string path) {
            var shortPath = new StringBuilder(MAX_PATH);
            GetShortPathName(path, shortPath, MAX_PATH);
            return shortPath.ToString();
        }
    

提交回复
热议问题