4

以下代码假设从我的 C# 应用程序打开 CMD 并打开文件 text.txt。

我试图将文件路径设置为环境变量,但是当记事本打开时,它会查找 %file%.txt 而不是 text.txt

知道为什么吗?

System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.EnableRaisingEvents=false;
        proc.StartInfo.EnvironmentVariables.Add("file", "c:\\text.txt");
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.FileName = "notepad";

        proc.StartInfo.Arguments="%file%";
        proc.Start();
        proc.WaitForExit();

        Console.WriteLine(proc.ExitCode);
4

8 回答 8

10

如果您的目的是使用 .txt 文件启动编辑器(如问题标题所示),只需使用:

Process.Start("C:\\text.txt")
于 2009-01-07T14:50:31.437 回答
3

简短的版本是我怀疑你将不得不更直接地传递 arg,即

 proc.StartInfo.Arguments = @"""c:\text.txt""";

虽然你可以设置环境变量(进程中使用),但我认为你不能在进程启动期间使用它们。

于 2009-01-07T14:35:46.413 回答
2

你想用 %file% 完成什么?notepad.exe 的命令行参数是您要打开的文件。你需要做这样的事情:

proc.StartInfo.Arguments = "c:\\text.txt";
于 2009-01-07T14:37:47.797 回答
1

一个明显的问题是您将 UseShellExecute 设置为 false。这意味着您正在直接执行记事本,而无需通过命令 shell cmd.exe 传递。因此环境变量没有被扩展。

我不确定您要实现什么(为什么需要添加环境变量?),但以下方法可行:

    System.Diagnostics.Process proc = 
        new System.Diagnostics.Process(); 
    proc.EnableRaisingEvents = false; 
    proc.StartInfo.EnvironmentVariables.Add("file", "c:\\text.txt"); 
    proc.StartInfo.UseShellExecute = false; 
    proc.StartInfo.FileName = "cmd.exe";
    proc.StartInfo.Arguments = "/c notepad %file%"; 
    proc.Start(); 
    proc.WaitForExit(); 
于 2009-01-07T14:34:21.843 回答
1

设置 UseShellExecute = true

这样它应该使用 cmd.exe 处理器来扩展 %file% 变量

于 2009-01-07T14:34:26.493 回答
0

尝试这个:

proc.StartInfo.Arguments = System.Environment.GetEnvironmentVariable("file");
于 2009-01-07T14:37:55.567 回答
0

也许它与 StartInfo.Arguments 的工作方式有关。如果你找不到更好的东西,这对我有用:

proc.StartInfo.FileName = "cmd";
proc.StartInfo.Arguments="/c notepad %my_file%";
于 2009-01-07T14:41:26.680 回答
0

我敢打赌你需要设置WorkingDirectory才能让它工作。 NOTEPAD.exe通常位于%SYSTEMROOT% (C:\windows)但默认为%SYSTEMROOT%\system32。试试下面的。

System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.EnableRaisingEvents=false;
        proc.StartInfo.WorkingDirectory = "%SYSTEMROOT%";
        proc.StartInfo.EnvironmentVariables.Add("file", "c:\\text.txt");
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.FileName = "notepad";

        proc.StartInfo.Arguments="%file%";
        proc.Start();
        proc.WaitForExit();

        Console.WriteLine(proc.ExitCode);
于 2009-01-07T15:04:56.727 回答