Skip to content

System.Diagnostics.Process long paths issues #58492

Open

Description

@krwq

Couple of issues related to using long paths with System.Diagnostics.Process

In all cases below I've used following ProcessStartInfo options:

ProcessStartInfo si = new();
si.WorkingDirectory = dir; // depending on case this line might have been skipped
si.FileName = file;

si.ArgumentList.Add("foo");
si.RedirectStandardOutput = true;
si.RedirectStandardError = true;
si.CreateNoWindow = true;
si.UseShellExecute = false;

// and then process started with:
Process process = Process.Start(si);
  • Starting a process by passing FileName into ProcessStartInfo where file name is a full path longer than MAX_PATH regardless of prefixing path with \\?\ always ends up with exception:
Click to see exception details When using `\\?\` prefix:
Unhandled exception. System.ComponentModel.Win32Exception (206): The filename or extension is too long.
   at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) in System.Diagnostics.Process.dll:token 0x600016a+0x37c
   at System.Diagnostics.Process.Start() in System.Diagnostics.Process.dll:token 0x600013f+0xab
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo) in System.Diagnostics.Process.dll:token 0x6000143+0x1b
   at ConsoleApp40.Program.Main(String[] args) in C:\Users\kwicher\source\repos\ConsoleApp40\x\ConsoleApp40\Program.cs:line 77

When using path directly:

Unhandled exception. System.ComponentModel.Win32Exception (2): The system cannot find the file specified.
   at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) in System.Diagnostics.Process.dll:token 0x600016a+0x37c
   at System.Diagnostics.Process.Start() in System.Diagnostics.Process.dll:token 0x600013f+0xab
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo) in System.Diagnostics.Process.dll:token 0x6000143+0x1b
   at ConsoleApp40.Program.Main(String[] args) in C:\Users\kwicher\source\repos\ConsoleApp40\x\ConsoleApp40\Program.cs:line 77
It's possible to workaround this issue by using `GetShortPathName`, i.e. (in this example shorten the path by using `GetFileName` method):
Click to expand code
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        private static unsafe extern int GetShortPathName(char* longPath, char* shortPath, int numChars);

        public static unsafe string GetFileName(string longPath)
        {
            longPath = Path.GetFullPath(longPath);
            const int MAX_PATH = 260;
            if (longPath.Length < MAX_PATH)
            {
                return longPath;
            }

            if (!longPath.StartsWith(@"\\?\"))
            {
                longPath = @"\\?\" + longPath;
            }

            fixed (char* longPathBuff = longPath)
            {
                int size = GetShortPathName(longPathBuff, null, 0);
                if (size == 0)
                {
                    // error, best attempt is to at least try with that path:
                    return longPath;
                }

                char[] buff = new char[size];
                fixed (char* shortPathBuff = buff)
                {
                    if (GetShortPathName(longPathBuff, shortPathBuff, size) == 0)
                    {
                        // error, best attempt:
                        return longPath;
                    }
                }

                return new string(buff);
            }
        }
  • When starting a process by passing just a file name (without directory) to FileName and directory to WorkingDirectory in the ProcessStructInfo this always throws an exception as well:
Click to see exception details

Regardless of using \\?\ prefix you get the same exception:

Unhandled exception. System.ComponentModel.Win32Exception (267): The directory name is invalid.
   at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) in System.Diagnostics.Process.dll:token 0x600016a+0x37c
   at System.Diagnostics.Process.Start() in System.Diagnostics.Process.dll:token 0x600013f+0xab
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo) in System.Diagnostics.Process.dll:token 0x6000143+0x1b
   at ConsoleApp40.Program.Main(String[] args) in C:\Users\kwicher\source\repos\ConsoleApp40\x\ConsoleApp40\Program.cs:line 78

Possibly same workaround as above could work to fix this although have not tried.

  • When using workaround from the first bullet point the arguments passed to ProcessStartInfo disappear, meaning that args in main has zero length even though arguments were passed - I have not digged into why this happens or where do they get lost

I've tried on netcoreapp3.1, net5.0 and net6.0 (preview) and seeing the same results.

Activity

  1. ghost added
    untriaged
    on Sep 1, 2021
  2. removed
    untriaged
    on Sep 1, 2021
  3. added this to the 7.0.0 milestone on Sep 1, 2021
  4. deeprobin commented on Apr 12, 2022

    @deeprobin
    Contributor

    I would assume based on the exception that this bug only occurs on Windows.
    Can you label this os-windows?

    Does the error also occur with ShellExecute, because internally different paths are chosen in the ShellExecute case?

    return startInfo.UseShellExecute
    ? StartWithShellExecuteEx(startInfo)
    : StartWithCreateProcess(startInfo);

    & does this also occur if specify a UserName, because this uses CreateProcessAsUserW afaik.

    Also, can you verify if this is due to the .NET API or simply a limitation of the WinAPI - See CreateProcessW?

  5. rseanhall commented on Jun 17, 2022

    @rseanhall
    Contributor

    I'm running into this issue, too. The problem is this line:

    null, // we don't need this since all the info is in commandLine

    According to the documentation:

    If lpApplicationName is NULL, the module name portion of lpCommandLine is limited to MAX_PATH characters.

    The code needs to pass the path to the executable into lpApplicationName as well so that it can be longer than MAX_PATH.

  6. RussKie commented on Jun 20, 2022

    @RussKie
    Contributor

    May be @JeremyKuhne has any insights?

  7. danmoseley commented on Jun 20, 2022

    @danmoseley
    Contributor

    The code needs to pass the path to the executable into lpApplicationName as well so that it can be longer than MAX_PATH.

    If this wouldn't break anyone, we'd welcome a PR.

    Does enabling long paths change behaviors:

    https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later

  8. rseanhall commented on Jun 20, 2022

    @rseanhall
    Contributor

    Does enabling long paths change behaviors

    No, at least as of the current Win11.

    If this wouldn't break anyone

    Yeah, about that... it turns out this probably can't be done in a non-breaking way.

    1. From the documentation: If the executable module is a 16-bit application, lpApplicationName should be NULL, and the string pointed to by lpCommandLine should specify the executable module as well as its arguments. I don't know how many .NET 7 applications will be running 16-bit .exes though.

    2. From the documentation: If lpApplicationName is NULL, ... If the file name does not contain an extension, .exe is appended. Therefore, if the file name extension is .com, this parameter must include the .com extension. If the file name ends in a period (.) with no extension, or if the file name contains a path, .exe is not appended. If the file name does not contain a directory path, the system searches for the executable file in the following sequence. None of this behavior is done when lpApplicationName is not null. I guess this could theoretically be worked around but it wouldn't be pretty.

    3. System.Diagnostics.Process tries to always add double quotes around the module name, but it is not properly ensuring that this happens. For example, if the file name is my exe then it will properly quote it as "my exe". But "my" "exe" will be left as is instead of properly escaping it to "\"my\" \"exe\"". On top of that, it currently accepts "my exe" as valid but if you pass "C:\my exe.exe" into lpApplicationName then CreateProcessW will literally look for "C:\my exe.exe" instead of C:\my exe.exe.

  9. danmoseley commented on Jun 20, 2022

    @danmoseley
    Contributor

    For (1) -- 16 bit support does not exist on 64 bit Windows. It's off by default on 32 bit Windows 10 apparently, and 32 bit Windows 11 doesn't exist. So at least in theory, it could safely work on those.

    But for (2) and (3) .. that does seem risky as you say.

  10. danmoseley commented on Jun 20, 2022

    @danmoseley
    Contributor

    What about only following this code path when we know the path is too long and will fail anyway? Or, conversely, when process start has failed and we believe this is why (eg error 206 when path is prefixed with \\?\) then try again with the other code path?

  11. rseanhall commented on Jun 20, 2022

    @rseanhall
    Contributor

    We would have to assume people weren't doing something crazy like putting all the arguments in the file name. "path\to\my.exe" assume all the arguments are longer than MAX_PATH "here" for example.

  12. JeremyKuhne commented on Jun 20, 2022

    @JeremyKuhne
    Member

    @danmoseley This could use some debugging on our part to see precisely what the limitations are. I did some quick looking at the current code (which is over 4000 lines) and didn't see many MAX_PATH references.

    • There is definitely a MAX_PATH restriction on lpCurrentDirectory if you specify it (which the original description does).
    • If lpApplicationName isn't present, the buffer for the file name (not path) is MAX_PATH, which should be fine.
    • If lpApplicationName isn't present, the heuristics it uses to figure out the unquoted exe name are impacted by MAX_PATH.
    • 16bit applications have a MAX_PATH limitation under PsCreateFailOnSectionCreate.

    A good article on the CreateProcess process can be found here.

    @rseanhall repro arguments would be useful.

  13. rseanhall commented on Jun 20, 2022

    @rseanhall
    Contributor

    Repro arguments for what exactly? All I was trying to point out was that because the current System.Diagnostics.Process code allows double quotes in the file name, it makes it impossible for us to tell whether the entire string is supposed to be the file name. So the ProcessStartInfo.FileName string might be more than MAX_PATH, but the actual file portion isn't. And if we try to parse the file name as if it's a command line, then we might run into issues because pathological cases like my.exe" arg1 "arg2 can work today (that will be changed to "my.exe" arg1 "arg2" before passing it to CreateProcess).

  14. JeremyKuhne commented on Jun 20, 2022

    @JeremyKuhne
    Member

    Repro arguments for what exactly?

    @rseanhall your repro of the MAX_PATH problem.

  15. rseanhall commented on Jun 21, 2022

    @rseanhall
    Contributor

    This is a simplified repro. The actual test is running our native executable to verify we have removed MAX_PATH limitations from it. That is a work in progress and will eventually be at https://github.com/wixtoolset/wix4.

    Edit:

    When long paths are disabled or not supported in the OS, Process.Start fails with ERROR_FILE_NOT_FOUND.

    Click to expand
    System.ComponentModel.Win32Exception : The system cannot find the file specified.
    Stack Trace:
       at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
       at System.Diagnostics.Process.Start()
       at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
    

    When long paths are enabled in the registry and .exe manifest, Process.Start fails with ERROR_FILENAME_EXCED_RANGE.

    Click to expand
    System.ComponentModel.Win32Exception : An error occurred trying to start process 'C:\Users\admin\AppData\Local\Temp\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\cmd.exe' with working directory 'C:\burn\longpath3'. The filename or extension is too long.
      Stack Trace:
       at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
       at System.Diagnostics.Process.Start()
       at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
    
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Text;
    using Xunit;
    
    namespace LongPathTests
    {
        
        public class Process
        {
            [Fact]
            public void CanStartProcessFromLongPath()
            {
                const int subdirLength = 100;
                var baseFolder = Path.Combine(Path.GetTempPath(), new string('a', subdirLength), new string('b', subdirLength), new string('c', subdirLength));
                Directory.CreateDirectory(baseFolder);
    
                try
                {
                    const string targetExe = "cmd.exe";
                    var sourceFile = new FileInfo(Path.Combine(Environment.SystemDirectory, targetExe));
                    var destFilePath = Path.Combine(baseFolder, targetExe);
                    sourceFile.CopyTo(destFilePath);
    
                    var exitCode = new Random().Next();
                    var psi = new ProcessStartInfo(destFilePath, $"/c exit /b {exitCode}")
                    {
                        CreateNoWindow = true,
                        RedirectStandardError = true,
                        RedirectStandardOutput = true,
                        UseShellExecute = false,
                        WorkingDirectory = string.Empty,
                    };
    
                    using (var process = Process.Start(psi))
                    {
                        var standardOutput = new StringBuilder();
                        var standardError = new StringBuilder();
    
                        process.ErrorDataReceived += (s, e) => { if (e.Data != null) { standardError.AppendLine(e.Data); } };
                        process.OutputDataReceived += (s, e) => { if (e.Data != null) { standardOutput.AppendLine(e.Data); } };
    
                        process.BeginErrorReadLine();
                        process.BeginOutputReadLine();
    
                        process.WaitForExit();
    
                        if (exitCode != process.ExitCode)
                        {
                            Assert.True(false, $"Expected exit code {exitCode}, but got {process.ExitCode}.\r\nOutput: {standardOutput}\r\nError: {standardError}");
                        }
                    }
                }
                finally
                {
                    Directory.Delete(baseFolder, true);
                }
            }
        }
    }
  16. rseanhall commented on Jun 22, 2022

    @rseanhall
    Contributor

    There is definitely a MAX_PATH restriction on lpCurrentDirectory if you specify it (which the original description does).

    Another thing to consider is that CreateProcessW tries to use the current directory of the current process if lpCurrentDirectory is NULL or an empty string. When long paths are enabled, the current directory can be longer than MAX_PATH. In this case, CreateProcessW fails with ERROR_INVALID_PARAMETER (87). You have to pass in a valid path less than MAX_PATH to avoid this error.

  17. deeprobin commented on Jun 23, 2022

    @deeprobin
    Contributor

    Does this also occur if lpCurrentDirectory is not NULL and the current work directory is longer than MAX_PATH?

  18. rseanhall commented on Jun 23, 2022

    @rseanhall
    Contributor

    I have only seen this when lpCurrentDirectory is NULL or an empty string.

  19. tannergooding commented on Jun 24, 2022

    @tannergooding
    Member

    We cannot consume APIs which are not publicly documented (generally this means documented on docs.microsoft.com).

    They are not publicly available and are not meant for direct consumption. The have no guarantees, can be removed at any time, and are effectively "private implementation detail".

  20. modified the milestones: 7.0.0, Future on Aug 9, 2022
  21. kazenshi commented on Dec 14, 2023

    @kazenshi

    Taken from the documentation here: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw#parameters

    [in, out, optional] lpCommandLine

    The command line to be executed.

    The maximum length of this string is 32,767 characters, including the Unicode terminating null character. If lpApplicationName is NULL, the module name portion of lpCommandLine is limited to MAX_PATH characters.

    This suggests when lpApplicationName is NULL then the lpCommandLine is limited to MAX_PATH

    Looking at the code for System.Diagnostics.Process it appears we pass NULL for lpApplicationName and I wonder if that could be what is triggering the MAX_PATH limit. Reference to places in code below.

    Here:
    https://github.com/dotnet/runtime/blob/07b6e338bb010b0dba1e72bdf546c69ade6f3f6c/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs#L555C33-L566C94

    And Here:
    https://github.com/dotnet/runtime/blob/07b6e338bb010b0dba1e72bdf546c69ade6f3f6c/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs#L583C29-L594C31

  22. kazenshi commented on Dec 14, 2023

    @kazenshi
  23. kazenshi commented on Dec 14, 2023

    @kazenshi

    I did some testing on my own and confirmed that adding lpApplicationName as well as lpCommandLine does not resolve the problem. lpCurrentDirectory is still limited by MAX_PATH. However, in addition I tested using the extended-length path prefix \\?\ which correctly functions as a path string but it ironically does not allow paths longer than MAX_PATH.

    Now if I pass a ShortPath string that resolves to a path longer than MAX_PATH it works correctly. https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getshortpathnamew

    Take the following 319-character longpath example:

    C:\tmp\longpathnamelongpathnamelongpathnamelongpathname\longpathnamelongpathnamelongpathnamelongpathname\longpathnamelongpathnamelongpathnamelongpathname\longpathnamelongpathnamelongpathnamelongpathnamelongpathnamelongpathnamelongpathnamelongpathn\longpathnamelongpathnamelongpathnamelongpath\longname\longname\longname

    If I pass it to GetShortPathName I receive the following path:

    C:\tmp\LONGPA~1\LONGPA~1\LONGPA~1\LONGPA~1\LONGPA~1\longname\longname\longname

    Passing the short path into the lpCurrentDirectory will resolve to the full path and start the application correctly. I tested this by using a dotnet console app to spawn powershell.exe. I confirmed it by checking the [Environment]::CurrentDirectory value in powershell and saw that it had resolved the short-path into the full long-path that exceeds the MAX_PATH limit

    I think this is a bug with CreateProcessW WinAPI and using short paths is simply a workaround.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions