简体   繁体   中英

How to redirect stdout of a C# project to file using the Visual Studio “command line arguments” option

I am trying to redirect the output of a C# program to a file. When using "cmd.exe" I can simply run it with myprogram.exe arg1 arg2 > out.txt , but I'd like to accomplish the same thing using Visual Studio Start Options .

I created a C# Empty Project and added this code:

using System;
class Test
{
    public static void Main(string[] args)
    {
        foreach (var arg in args) Console.WriteLine(arg);
    }
}

Then I edited the command line arguments in the Project Settings: 项目属性

Running the project with Ctrl+F5 does not work as intended. I get the command line arguments printed in the console and not in the output file:

arg1
arg2
>
output.txt

If I change the command line arguments to: arg1 arg2 "> output.txt" I get the following output:

arg1
arg2
^> output.txt

I noticed that an empty output.txt file gets created in the Output folder.

Is this thing possible to accomplish or am I forced to keep using cmd.exe to launch my program?

In the strict sense, you are forced to use the command prompt to start the program with redirected output. Otherwise, you would need to parse the command line yourself, the GUI shell might not do that.

If you just want to redirect the output when you Start Debugging , then uncheck the check box of Enable the Visual Studio hosting process , you are done.

If you did not, and the "output.txt" you've seen there, in fact, is not generated by your application, but "YourApplication.vshost.exe" which is spawned before you started to debug, by Visual Studio IDE. The content would always be empty, and cannot be written; because it's locked by the Hosting Process .

fo1e8.png

However, if you want the application behaves as the same whatever the mode you start it, things are more complicated.

When you start debugging with the application, it's started with:

"YourApplication.exe" arg1 arg2

because the output is already redirected by the IDE.

And when you Start Without Debugging , it's started with:

"%comspec%" /c ""YourApplication.exe" arg1 arg2 ^>output.txt & pause"

This is the correct way to let your application gets all the arguments which you specified.

You might want to have a look at my previous answer of How can I detect if "Press any key to continue . . ." will be displayed? .

Here I'm using an approach like atavistic throwback in the code below:

  • Code of application

     using System.Diagnostics; using System.Linq; using System; class Test { public static void Main(string[] args) { foreach(var arg in args) Console.WriteLine(arg); } static Test() { var current=Process.GetCurrentProcess(); var parent=current.GetParentProcess(); var grand=parent.GetParentProcess(); if(null==grand ||grand.MainModule.FileName!=current.MainModule.FileName) using(var child=Process.Start( new ProcessStartInfo { FileName=Environment.GetEnvironmentVariable("comspec"), Arguments="/c\\x20"+Environment.CommandLine, RedirectStandardOutput=true, UseShellExecute=false })) { Console.Write(child.StandardOutput.ReadToEnd()); child.WaitForExit(); Environment.Exit(child.ExitCode); } #if false // change to true if child process debugging is needed else { if(!Debugger.IsAttached) Debugger.Launch(); Main(Environment.GetCommandLineArgs().Skip(1).ToArray()); current.Kill(); // or Environment.Exit(0); } #endif } } 

We also need the following code so that it can work:

  • Code of extension methods

     using System.Management; // add reference is required using System.Runtime.InteropServices; using System.Diagnostics; using System.Collections.Generic; using System.Linq; using System; public static partial class NativeMethods { [DllImport("kernel32.dll")] public static extern bool TerminateThread( IntPtr hThread, uint dwExitCode); [DllImport("kernel32.dll")] public static extern IntPtr OpenThread( uint dwDesiredAccess, bool bInheritHandle, uint dwThreadId); } public static partial class ProcessThreadExtensions /* public methods */ { public static void Abort(this ProcessThread t) { NativeMethods.TerminateThread( NativeMethods.OpenThread(1, false, (uint)t.Id), 1); } public static IEnumerable<Process> GetChildProcesses(this Process p) { return p.GetProcesses(1); } public static Process GetParentProcess(this Process p) { return p.GetProcesses(-1).SingleOrDefault(); } } partial class ProcessThreadExtensions /* non-public methods */ { static IEnumerable<Process> GetProcesses( this Process p, int direction) { return from format in new[] { "select {0} from Win32_Process where {1}" } let selectName=direction<0?"ParentProcessId":"ProcessId" let filterName=direction<0?"ProcessId":"ParentProcessId" let filter=String.Format("{0} = {1}", p.Id, filterName) let query=String.Format(format, selectName, filter) let searcher=new ManagementObjectSearcher("root\\\\CIMV2", query) from ManagementObject x in searcher.Get() let process= ProcessThreadExtensions.GetProcessById(x[selectName]) where null!=process select process; } // not a good practice to use generics like this; // but for the convenience .. static Process GetProcessById<T>(T processId) { try { var id=(int)Convert.ChangeType(processId, typeof(int)); return Process.GetProcessById(id); } catch(ArgumentException) { return default(Process); } } } 

Since the parent would be Visual Studio IDE(currently named "devenv" ) when we are debugging. The parent and grandparent process in fact are various, and we would need a rule to perform some checking.

The tricky part is that the grandchild is the one really runs into Main . The code check for the grandparent process each time it runs. If the grandparent was null then it spawns, but the spawned process would be %comspec% , which is also the parent of the new process it going to start with the same executable of current. Thus, if the grandparent are the same as itself then it won't continue to spawn, just runs into Main .

The Static Constructor is used in the code, which is started before Main . There is an answered question on SO: How does a static constructor work? .

When we start debugging, we are debugging the grandparent process(which spawns). For debugging with the grandchild process, I made Debugger.Launch with a conditional compilation which will invoke Main , for keeping Main clear.

An answered question about the debugger would also be helpful: Attach debugger in C# to another process .

I not sure if this can be done in Visual Studio. My solution would be to set a new output for the console. This example is from the MSDN:

Console.WriteLine("Hello World");
FileStream fs = new FileStream("Test.txt", FileMode.Create);
// First, save the standard output.
TextWriter tmp = Console.Out;
StreamWriter sw = new StreamWriter(fs);
Console.SetOut(sw);
Console.WriteLine("Hello file");
Console.SetOut(tmp);
Console.WriteLine("Hello World");
sw.Close();

http://msdn.microsoft.com/en-us/library/system.console.setout.aspx

In the Start Options section, change your command line arguments textbox in this way

args1 args2 1>output.txt

This redirects the standard output (1) creating a file named output.txt
If you want to append to a previous version of the file write

args1 args2 1>>output.txt

Now you can debug the program Step-by-Step while the output console is redirected

I would suggest a better way without of need to writing any piece of code!

启动设置

Just config visual studio to start your program as an external program.

You can open the .csproj.user in an external editor and change the StartArguments from:

<StartArguments>arg1 arg2 &gt; output.txt</StartArguments>

to

<StartArguments>arg1 arg2 > output.txt</StartArguments>

you are going to have to continue to use cmd.exe if you want to pipe your output to a file. the Command line arguments: is for command line arguments, therefore anything you try will be escaped to be a command line argument. Pipes and redirectors are not command line arguments, therefore they are getting escaped.

I would just create a .bat file that calls the program how I like. You could pin that to the taskbar and simply run it.

The simple way is: Right click on the Project => Properties ==> Debug

在此输入图像描述

And then make sure to run your program in Debug mode .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM