How to shorten a path in c# and keep it valid

十年热恋 提交于 2020-02-24 14:57:09

问题


I work in a place where directories have such a looong name and are in such a looong tree.

And I'm having problems with too long path names for folders in an external applicatoin (I can't change this external application, but I can give it shortened path names).

I know Microsoft operating systems can shorten path names such as transforming C:\TooLongName\TooLongSubDirectory in something like C:\TooLon~1\TooLon~1.

But how can I do this in C# and still keep the nave valid and usable?

PS: I'm not using the standard FileInfo and DirectoryInfo classes, I'm using just strings that will be sent to an external application that I cannot change in any way.


回答1:


If you are unable to use the long path support build into Windows 10 you are able to use the Win32 command GetShortPathName . In order to generate a suitable path.

class Program
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern uint GetShortPathName(
       [MarshalAs(UnmanagedType.LPTStr)]
       string lpszLongPath,
       [MarshalAs(UnmanagedType.LPTStr)]
       StringBuilder lpszShortPath,
       uint cchBuffer);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern uint GetShortPathName(string lpszLongPath, char[] lpszShortPath, int cchBuffer);

    static void Main(string[] args)
    {
        StringBuilder builder = new StringBuilder(260);
        var shortPath = GetShortPathName(@"C:\Projects\Databases\ReallllllllllllllyLOOOOOOOOOOOOOOOOOOOOOONGPATHHHHHHHHHHH\StillllllllllllllllllGOoooooooooooooooooooooooing", builder, (uint)builder.Capacity);
        Console.WriteLine(builder.ToString());
        Console.ReadKey();
    }
}

Produces C:\Projects\DATABA~1\REALLL~1\STILLL~1



来源:https://stackoverflow.com/questions/45549888/how-to-shorten-a-path-in-c-sharp-and-keep-it-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!