从 C# 应用程序打开 txt 文件
以下代码假设从我的 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);
The following code is suppose to open CMD from my C# application and open the file text.txt.
I tried to set the file path as an environment variable but when notepad opens it looks for %file%.txt instead of text.txt
Any idea why?
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果您的目的是使用 .txt 文件启动编辑器(如问题标题所示),只需使用:
If your purpose is to start the editor with a .txt file (like the title of the question says) just use:
简而言之,我怀疑您必须更直接地传递 arg,即
虽然您可以设置环境变量(用于在进程内使用),但我认为您不能使用它们在过程启动期间。
The short version is that I suspect you are going to have to pass the arg more directly, i.e.
Although you can set environment variables (for use within the process), I don't think you can use them during the process start.
您想用 %file% 实现什么目的? notepad.exe 的命令行参数是您要打开的文件。 你需要做这样的事情:
What are you trying to accomplish with %file%? The command line argument for notepad.exe is the file you want to open. You need to do something like this:
设置 UseShellExecute = true
这样它应该使用 cmd.exe 处理器来扩展 %file% 变量
set UseShellExecute = true
that way it should use the cmd.exe processor to expand the %file% variable
一个明显的问题是您将 UseShellExecute 设置为 false。 这意味着您直接执行记事本,而不通过命令外壳 cmd.exe。 因此环境变量不会被扩展。
我不确定您想要实现什么目标(为什么需要添加环境变量?),但以下内容可行:
One obvious problem is that you have UseShellExecute set false. This means you are executing notepad directly without passing via the command shell cmd.exe. Therefore environment variables aren't being expanded.
I'm not sure what you're trying to achieve (why do you need to add an environment variable?) but the following would work:
尝试这个:
Try this:
也许这与 StartInfo.Arguments 的工作方式有关。 如果你找不到更好的东西,这对我有用:
Perhaps it has to do with how the StartInfo.Arguments work. If you can't find anything better, this worked for me:
我敢打赌您需要设置 WorkingDirectory 才能使其正常工作。 NOTEPAD.exe 通常位于%SYSTEMROOT% (C:\windows),但默认位置为%SYSTEMROOT%\system32。 尝试下面的方法。
I am willing to bet you need to set WorkingDirectory to get this to work. NOTEPAD.exe is usually located in %SYSTEMROOT% (C:\windows) however the default is %SYSTEMROOT%\system32. Try out the below.