4

我在 DOS 命令进程中启动了一个 C# 控制台可执行文件。

我需要能够从 C# 可执行文件执行 DOS 命令(特别是我需要能够设置变量)并使变量保持不变,以便 DOS 进程的其余部分可以引用它们。

IE:

启动 DOS 进程 -> C# 执行 SET 命令设置 UserVariable -> DOS 进程可以 ECHO %UserVariable%

由于性能原因,我无法将 set 命令写入 dos 脚本。事实上,我根本没有任何文件 I/O。

任何人都可以帮忙吗?

4

6 回答 6

4

SETX 保留环境变量。检查这个:http ://technet.microsoft.com/es-es/library/cc755104(v=ws.10).aspx

于 2012-06-14T14:59:30.693 回答
3

The problem isn't with the fact that you are calling SET from within a C# application. Even if you open a windows prompt and call SET to set a user variable, it will not persist through sessions.

Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.

Source.

I advise you to set variables directly through .Net, anyway. You can use Environment.SetEnvironmentVariable to do this.

于 2012-06-14T15:01:04.530 回答
1

If you are running a C# app from a dos script and wishing to use variables set in the app afterwards from the script, I don't know how to do that for just the context of that script from within C#, the other answers here show you for the machine itself but I appreciate you need something with a less permanent scope.

A meta-programming workaround this could be to:

  • Call the C# app from a DOS FOR loop
  • From the C# app, output to the console SET commands
  • Use the for loop to execute the app output

The calling DOS script would look like this:

FOR /F "tokens=* delims=" %%A IN ('MyApp.exe') DO ( 
   %%A
)

The Console output from MyApp.exe would need to be in the form:

SET UserVariable1=UserValue1
SET UserVariable2=UserValue2

And then each of the output lines would be executed by the calling FOR loop and the variables would then exist in the context of the calling script.

于 2012-06-21T14:37:32.650 回答
1

Use the following .NET method instead:

Environment.SetEnvironmentVariable

于 2012-06-14T15:00:47.320 回答
0

这绝不是一个答案,但从问题的性质来看,这种“妥协”是我们暂时选择的路径。

我们将使用由 C# 应用程序创建的批处理脚本,该脚本将包含所需的所有简单设置命令,然后由调用 C# 应用程序的 CMD 进程执行。

请随时添加任何进一步的想法和评论,因为这不是理想的解决方案。

于 2012-06-15T13:54:13.827 回答
-1

Unfortunately, so far as I can tell, this is the "solution" that is available, through at least Windows 7. I've been experimenting with various ways to set and subsequently use environment variables, and the bottom line of my research is that, if you want to use a variable, it must either be set in advance into the USER or MACHINE key, or it must be a local variable, set by script command, then tested further along in the same script.

So far as I am concerned, the third element in that enumeration, Process, is essentially useless. The only way that I can see that it might be useful is if a process spawns another process, passing its environment to the child process. That's overkill for most run-of-the-mill administrative scripts.

于 2012-08-24T01:25:03.240 回答