Repository navigation
Open
Milestone
Description
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
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
FileNameand directory toWorkingDirectoryin 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
argsin 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.
Reacted by 两米
Activity
deeprobin commentedon Apr 12, 2022
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?runtime/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs
Lines 25 to 27 in 42044c6
& 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?rseanhall commentedon Jun 17, 2022
I'm running into this issue, too. The problem is this line:
runtime/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs
Line 569 in bfceef9
According to the documentation:
The code needs to pass the path to the executable into
lpApplicationNameas well so that it can be longer thanMAX_PATH.RussKie commentedon Jun 20, 2022
May be @JeremyKuhne has any insights?
danmoseley commentedon Jun 20, 2022
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
rseanhall commentedon Jun 20, 2022
No, at least as of the current Win11.
Yeah, about that... it turns out this probably can't be done in a non-breaking way.
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.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 whenlpApplicationNameis not null. I guess this could theoretically be worked around but it wouldn't be pretty.System.Diagnostics.Processtries to always add double quotes around the module name, but it is not properly ensuring that this happens. For example, if the file name ismy exethen 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"intolpApplicationNamethenCreateProcessWwill literally look for"C:\my exe.exe"instead ofC:\my exe.exe.danmoseley commentedon Jun 20, 2022
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.
danmoseley commentedon Jun 20, 2022
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?rseanhall commentedon Jun 20, 2022
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.JeremyKuhne commentedon Jun 20, 2022
@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_PATHreferences.MAX_PATHrestriction onlpCurrentDirectoryif you specify it (which the original description does).lpApplicationNameisn't present, the buffer for the file name (not path) isMAX_PATH, which should be fine.lpApplicationNameisn't present, the heuristics it uses to figure out the unquoted exe name are impacted byMAX_PATH.MAX_PATHlimitation underPsCreateFailOnSectionCreate.A good article on the
CreateProcessprocess can be found here.@rseanhall repro arguments would be useful.
rseanhall commentedon Jun 20, 2022
Repro arguments for what exactly? All I was trying to point out was that because the current
System.Diagnostics.Processcode 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 theProcessStartInfo.FileNamestring 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 likemy.exe" arg1 "arg2can work today (that will be changed to"my.exe" arg1 "arg2"before passing it toCreateProcess).JeremyKuhne commentedon Jun 20, 2022
@rseanhall your repro of the
MAX_PATHproblem.rseanhall commentedon Jun 21, 2022
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
When long paths are enabled in the registry and .exe manifest, Process.Start fails with ERROR_FILENAME_EXCED_RANGE.
Click to expand
rseanhall commentedon Jun 22, 2022
Another thing to consider is that
CreateProcessWtries to use the current directory of the current process iflpCurrentDirectoryis NULL or an empty string. When long paths are enabled, the current directory can be longer thanMAX_PATH. In this case,CreateProcessWfails withERROR_INVALID_PARAMETER(87). You have to pass in a valid path less thanMAX_PATHto avoid this error.deeprobin commentedon Jun 23, 2022
Does this also occur if
lpCurrentDirectoryis not NULL and the current work directory is longer thanMAX_PATH?rseanhall commentedon Jun 23, 2022
I have only seen this when
lpCurrentDirectoryis NULL or an empty string.tannergooding commentedon Jun 24, 2022
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".
kazenshi commentedon Dec 14, 2023
Taken from the documentation here: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw#parameters
This suggests when
lpApplicationNameis NULL then thelpCommandLineis limited toMAX_PATHLooking at the code for
System.Diagnostics.Processit appears we passNULLforlpApplicationNameand I wonder if that could be what is triggering theMAX_PATHlimit. 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
kazenshi commentedon Dec 14, 2023
kazenshi commentedon Dec 14, 2023
I did some testing on my own and confirmed that adding
lpApplicationNameas well aslpCommandLinedoes not resolve the problem.lpCurrentDirectoryis still limited byMAX_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 thanMAX_PATH.Now if I pass a
ShortPathstring that resolves to a path longer thanMAX_PATHit works correctly. https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getshortpathnamewTake the following 319-character longpath example:
If I pass it to
GetShortPathNameI receive the following path:Passing the short path into the
lpCurrentDirectorywill resolve to the full path and start the application correctly. I tested this by using a dotnet console app to spawnpowershell.exe. I confirmed it by checking the[Environment]::CurrentDirectoryvalue in powershell and saw that it had resolved the short-path into the full long-path that exceeds theMAX_PATHlimitI think this is a bug with
CreateProcessWWinAPI and using short paths is simply a workaround.