Write To Standard Output When No Console Present - c#

Console.Write* works as expected when used with a console application, or a windowed application with a console attached.
However, if I make an application that does not have a console and run it from the command line, it does not output as expected. It appears to start the application asynchronously as the prompt reappears while the program is still running.
How can I output in such a way that text output will appear in an attached console or a command prompt that runs it? Or, how do I run the application differently where it waits correctly and captures the expected output?

Consider using a Logger framework, rather than relying on Console. Logging frameworks provide a variety of ways to consume their logs, so you can decide which way works best for you without having to change your code.
For example, if you're using a logging framework that's set to output log messages to the console for the sake of a console app, you only have to change one configuration option to make it output to a file, which you can use a tool like Baretail to watch even if you don't have the console open. Or you can easily change the configuration to output to System.Diagnostics.Debug so that it appears in the Visual Studio Output window.

If you're just wanting debug output to appear in Visual Studio, use System.Diagnostics.Debug.WriteLine() to output to the "Immediate" window in VS while the application is running. Wrap is in "IF" precompiler directives so that it won't happen when you compile into a non-debug build. Any lines inside the "IF" will be completely ignored by the compiler if the current build target does not have the "DEBUG" flag set (like the default "Release" build target).
#if DEBUG
System.Diagnostics.Debug.WriteLine()
#endif

Related

C# Console.Write shows nothing VS Studio, how to System.Out.Println [duplicate]

I am trying to write a message to the output window for debugging purposes. I searched for a function like Java's system.out.println(""). I tried Debug.Write, Console.Write, and Trace.Write. It does not give an error, but it does not print anything either.
"Define DEBUG constant" and "Define TRACE constant" options are checked.
Menu Tools → Options → Debugging → "Redirect all Output Window text to the Immediate Window" option is not checked.
Configuration: Active (Debug)
Note: I created a project with the wizard as "Windows Forms Application" if relevant. I have no idea where to look.
Add the System.Diagnostics namespace, and then you can use Debug.WriteLine() to quickly print a message to the output window of the IDE. For more details, please refer to these:
How to trace and debug in Visual C#
A Treatise on Using Debug and Trace classes, including Exception Handling
This will write to the debug output window:
using System.Diagnostics;
Debug.WriteLine("Send to debug output.");
Debug.WriteLine
is what you're looking for.
If not, try doing this:
Menu Tools → Options → Debugging → uncheck Send Output to Immediate.
For me, only the Trace namespace and not the Debug one worked:
System.Diagnostics.Trace.WriteLine("message");
I'm working in a C# project under Visual Studio 2010.
You may be looking for
MessageBox.Show()
or
Debug.Writeline()
The call
System.Diagnostics.Debug.WriteLine("message");
fails when working with .NET Core (V 1.0 or 1.1).
We are supposed to create and use a logger from Microsoft.Extensions.Logging, but that log only appears in the dotnet.exe popup console window, not in Visual Studio's Output window.
This requires a third party framework, namely Serilog, but I've nonetheless found it to be a very smooth experience with getting output to some place I can see it.
You first need to install Serilog's Trace sink. Once installed, you need to set up the logger like this:
Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.Trace()
.CreateLogger();
(You can set a different minimum level or set it to a config value or any of the normal Serilog functionality. You can also set the Trace logger to a specific level to override configs, or however you want to do this.)
Then you just log messages normally and they show up in your Output window:
Logger.Information("Did stuff!");
This doesn't seem like such a big deal, so let me explain some additional advantages. The biggest one for me was that I could simultaneously log to both the Output window and the console:
Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.Trace()
.WriteTo.Console(standardErrorFromLevel: LogEventLevel.Error)
.CreateLogger();
This gave me great flexibility in terms of how I consumed output, without having to duplicate all my calls to Console.Write with Debug.Write. When writing the code, I could run my command line tool in Visual Studio without fear of losing my output when it exited. When I had deployed it and needed to debug something (and didn't have Visual Studio available), the console output was readily available for my consumption. The same messages can also be logged to a file (or any other kind of sink) when it's running as a scheduled task.
The bottom line is that using Serilog to do this made it really easy to dump messages to a multitude of destinations, ensuring I could always readily access the output regardless of how I ran it.
It also requires very minimal set up and code.
For debugging purposes, the System.Diagnostics.Debug.WriteLine() command will not be compiled into the release version of your code unless you have debug listeners. It writes to all trace listeners which includes the VS output window when running in Debug mode.
For a Console application. Console.WriteLine() would work but the output would still be generated in the release version of your binary.
Debug output should also appear in the normal output window when debugging tests; whereas, console.writeline output does not (but can be found in the test output window.)
This is not an answer to the original question. But since I found this question when searching for a means of interactively dumping object data, I figured others may benefit from mentioning this very useful alternative.
I ultimately used the Command Window and entered the Debug.Print command, as shown below. This printed a memory object in a format that can be copied as text, which is all I really needed.
> Debug.Print <item>
id: 1
idt: null
igad: 99
igbd: 99
gl_desc: "New #20"
te_num: "1-001-001-020"
Debug.Print("text here")
or
Console.WriteLine("text here")
The following worked for me in Visual Studio 2015:
OutputDebugStringW(L"Write this to Output window in VS14.");
Read the documentation for OutputDebugStringW here.
Note that this method only works if you are debugging your code (debug mode)
For anyone using NCrunch, Debug output is redirected to the NCrunch 'Trace Output' window.

Hololens: no debug output in Visual Studio 2017

My task is very simple, I put in the Main method two lines:
Debug.Log("App START Debug.Log");
Debug.unityLogger.Log("App", "START Debug.unityLogger.Log");
and want to see these logs in the output if the app is running. If I set the run option as Releasethe app starts, but I don't see these logs. If I set the run option as Debug and try to start, I get an error popup:
Unable to activate Windows Store app ´Template3D_pzq3xp76mxafg!App´
and the app doesn't start at all.
EDIT: according to comment of #Perazim, I have also tried:
System.Diagnostics.Debug.WriteLine("App START Debug.Log");
No effect in Release and Debug mode.
EDIT 2:
System.Diagnostics.Debug.WriteLine("App START Debug.Log");
works, if I put it in other methods, but doesn't work in the Main() method.
Debugger.Log for the output to debugger. Debug.WriteLine prints to listeners. If there is no listeners, it will not work.
My application stopped writing output to the output window with the System.Diagnostics.Debug.Writeline in debug mode. This all happened after the latest Microsoft Updates.
I created a new application just to see if it was my current application, and the new application would not write to the output window either.
Then I decided to right click on the Output Pane in Visual Studio and what do I see, Program Output unchecked.
I checked this and my Debug.Writeline works again.
In unity you can use/see debug.log(); in Visual Studio you need to use Console.WriteLine();

Setting save in c#

I have a problem with c# settings...
I have a string in Setting and call it UserStr
when I debug my program, I can change and use it without any problems:
using it:
var str=Properties.Setting.Default.Userstr;
changing it:
Properties.Setting.Default.UserStr="SomeTextbox.Text";
Properties.Setting.Default.Save();
and it works fine...
but when I run the debugged program from debug folder,the value of UserStr is the default value I set in first place...
Am I doing anything wrong?
Am I doing anything wrong?
No, this is just how the debugger works. You likely have the Visual Studio hosting process enabled (it is enabled by default). The settings manager uses the .exe as the key for the directory where the settings are stored.
The result of this is that you actually have two different settings files. One that's used when you run the program standalone, and one that's used when you run the program under the debugger, because in each case a different process .exe is actually what's running.
In many cases, you can live without the hosting process. It can be disabled in the project settings, under the Debug tab. Uncheck the checkbox labeled "Enable the Visual Studio hosting process". If you do so, then even when debugging the process .exe will be your actual program, and it will use the same settings file as when the program is used standalone.
Personally, I'd leave things as they are. I don't usually find it a problem to have two different settings files in use. I typically am not running the program standalone until debugging is, for the most part, over with.
See What is the purpose of vshost.exe file? for more details.
Just try:
Properties.Settings.Default.Reload();

Is there a better way to run a c++ makefile from a c# project?

I have a project in c# which uses bindings to use some c++ code. The c++ code consists of multiple DLL's which are compiled using a makefile. Currently I'm trying to run the makefile using a pre build event which calls nmake. However to get it to find nmake I need to have a line in it like the following:
"$(DevEnvDir)..\..\VC\vcvarsall.bat"
Also, even with that line present, nmake doesn't produce any output at all in the output window. Neither does it throw any errors. I tried redirecting the output to a file and it doesn't write anything. I have reproduced all steps in my pre build event in a normal shell and it works fine. I figure I must be missing something. Why doesn't Visual Studio give me a Visual Studio shell for my pre build event? Is there a better way to run this makefile? If not, has anyone got any ideas as to why nmake isn't producing any output?
EDIT: D'oh! nmake wasn't running as I forgot to add 'call' to the start of the line, i.e:
call "$(DevEnvDir)..\..\VC\vcvarsall.bat"
I often build non VS-project (sometimes with nmake, sometimes with other build tools) as a part of a larger solution build.
I tend to make a simple batch file, which sets up the environment and then runs the make.
I call the batch file from a build event (often post-build on my stuff) - usually with a CD on the front:
cd ..\.. && armbuild
Never (that I can remember, anyway) had any problem with the output appearing in the console window.

How does VS compile console applications to show "Press any key to continue"?

When I develop a C# console application (which will run on a server) and I run it using Visual Studio, I get a "Press any key to continue" message before the program terminates.
However, when I compile the very same C# code file manually using CSC, my program doesn't show that message and it terminates immediately after finishing its logic.
Does anyone know how I can make the same feature when compiling the code without using VS and WITHOUT changing the C# code any adding a ReadLine()?
UPDATE : The same message used to appear when I learned C#, I used to use TextPad with CSC, and that message used to appear without adding any Write(Line)/Read(Line) callings
It's nothing to do with the compiler - if you press F5 to debug it rather than Ctrl-F5 to run without debugging, then VS doesn't show the prompt. This is presumably so that you don't miss whatever output it's producing.
In order to do this, Visual Studio runs cmd.exe telling it to run your executable and then pause:
"C:\WINDOWS\system32\cmd.exe" /c ""...\ConsoleApplication1.exe" & pause"
It probably doesn't do it when you debug as it's a bit harder to get the process ID of a child of a child process.
To add a similar option to your program, either use a command line switch to tell the application itself to pause, or use a batch file to run it then pause, or use a shortcut with them cmd.exe /c.
That's not possible. The prompt to press any key is generated by Visual Studio when running a console app. It's not part of your program.
The only way is by using Console.Read() in your code
UPDATE: concerning your remark on using TextPad: I'm not familiar with TextPad, but I wouldn't be surprised if TextPad did the same thing as Visual Studio when running a console app.
You could do this...
static void Main(string[] args)
{
#if DEBUG
Console.Read();
#endif
}
That way the program will not wait for the console input when you build your application as a 'Release'.
You could write a batch script that runs the exe for you and prompts the user to press a key.
The batch script would look something like this:
echo off
YourApp.exe
pause
You could do this, if you want the same functionality when debugging.
if (Debugger.IsAttached)
{
Console.WriteLine("Press any key to continue . . . ");
Console.ReadKey(true);
}
This behavior has nothing to do with the compiler you are using. When you compile with Visual Studio, running the executable outside of Visual Studio actually will perform exactly the same as when you compile with CSC on the command line. Visual Studio (and TextPad) is adding the logic to add the "Press any key to continue" message on the console.
If you want your application to stay open, you will need to do something like Console.ReadLine() to block execution so that your application does not complete its execution.
The question is why would you want to have this behaviour? The Press any key to continue feature is there so that you can see the output of your application. If on the other hand you build your code and run it from a command prompt (console), this will not close when the application finishes, so you can see the output.
As noted above, the Press any key to continue is a feature of the IDE and not related to the code you are writing. The purpose of that feature is to allow you to see the output of you console application.

Categories

Resources