Search code examples
c#windowspathpathtoolongexception

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


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.


Solution

  • 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