14

我试图在运行 Vista 并启用了 UAC 的 2 台不同计算机中以具有管理员权限的不同用户身份运行进程,但在其中一台计算机中,我得到一个 Win32Exception,显示“目录名称无效”

谁能告诉我我的代码有什么问题?

var myFile = "D:\\SomeFolder\\MyExecutable.exe";
var workingFolder = "D:\\SomeFolder";
var pInfo = new System.Diagnostics.ProcessStartInfo();
pInfo.FileName = myFile;
pInfo.WorkingDirectory = workingFolder;
pInfo.Arguments = myArgs;
pInfo.LoadUserProfile = true;
pInfo.UseShellExecute = false;
pInfo.UserName = {UserAccount};
pInfo.Password = {SecureStringPassword};
pInfo.Domain = ".";

System.Diagnostics.Process.Start(pInfo);

更新

执行上述代码的应用程序具有 requireAdministrator 执行级别。我什至将工作文件夹设置为“Path.GetDirectoryName(myFile)”“New System.IO.FileInfo(myFile).DirectoryName”

4

6 回答 6

18

您需要指定WorkingDirectoryProcessStartInfo 的属性。来自Win32Exception 错误代码 267“目录名称无效”

我目前正在开发“自动运行方式”工具。它的目标是帮助像我一样必须为用户提供一种以管理员身份执行一个或两个程序的方法并且希望这样做而不必交出管理员密码的管理员。

So, I'm developing on Vista and I just whipped up a small proof of concept prototype, that'd run calc.exe as a different user, using ProcessStartInfo and Process. This worked fine when I executed it as myself (a rather pointless exercise, I must admit), but when I created a new user and tried to run it as him, I stumbled upon a Win32Exception complaining that the directory name is invalid, native error code 267. I was instsantly baffled, as I knew of no supplied directory name that could be invalid. I then tested the code on an XP machine and it worked!

I started googling on it to no avail, many reports of that error but no conclusive solution, or on different contexts. Finally, after a while it dawned on me, I wasn't specifying the WorkingDirectory property of the ProcessStartInfo class, as soon as I added the lines

FileInfo fileInfo = new FileInfo(path); startInfo.WorkingDirectory = fileInfo.DirectoryName;

To my code, it was allowed to run code as different than logged in user. ...

于 2014-08-01T04:41:11.210 回答
5

这是因为文件的路径长度超过了 255 个字符。

于 2010-04-12T12:20:11.063 回答
4

尝试更换

pInfo.WorkingDirectory = New System.IO.FileInfo(myFile).DirectoryName;

pInfo.WorkingDirectory = Path.GetDirectoryName(myFile);

FileInfo 可以访问文件系统,我假设只有管理员用户可以访问该目录。如果它不能解决你的问题,至少它会让你的代码更快一点......

于 2009-06-13T13:16:44.617 回答
3

该目录是登录用户的映射主文件夹还是低于该目录?这篇知识库文章可能会有所帮助:

当您使用 Windows 中的运行方式功能启动 Cmd.exe 或 Notepad.exe 时出现“目录名称无效”错误消息

更新:请注意,作为本地管理员组的成员和拥有管理权限在 Vista 上是不同的。

我想当您以管理员身份运行 C# 应用程序时一切正常。右键单击可执行文件,然后选择Run as Administrator,或从提升的命令提示符启动应用程序(获得的最快方法是按Start,输入 'cmd' 然后输入Ctrl+Shift+Return)。

或者,作为替代方案,为运行该进程的帐户禁用 UAC。

于 2009-06-13T12:47:28.383 回答
2

这是由于文件夹名称中的空格。一旦我删除了空间,当我遇到这个问题时它开始工作文件。

于 2010-12-08T21:36:07.803 回答
2

我有类似的经历,结果证明是我们的开发环境存在问题。我们使用 subst 命令将源代码目录映射到虚拟驱动器。所以 FileName 和 WorkingDirectory 属性被设置为“W:\SomeFolder\FileName.exe”

当我硬编码文件名和工作目录以通过我的实际磁盘 (C:) 访问文件时,我停止接收“无效目录”异常。

于 2011-08-09T16:31:12.150 回答