.net Console.WriteLine 去哪里调试?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/250404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where does Console.WriteLine go in Debug?
提问by ripper234
I found this question, but what I want to know is different - does the output from Console.WriteLine go anywhere when debugging? I know that for it to go to the output window I should should Debug.WriteLine() or other methods, but where does the standard Console.WriteLine() go?
我发现了这个问题,但我想知道的是不同的 - Console.WriteLine 的输出在调试时会去任何地方吗?我知道要让它进入输出窗口,我应该使用 Debug.WriteLine() 或其他方法,但是标准的 Console.WriteLine() 去哪里了?
EditWhen debugging, you don't see the black console window / test log - so the real question ishow can I access/view this output during debugging?
编辑调试时,您看不到黑色控制台窗口/测试日志 - 所以真正的问题是如何在调试期间访问/查看此输出?
回答by Carl R
The console can redirect it's output to any textwriter. If you implement a textwriter that writes to Diagnostics.Debug, you are all set.
控制台可以将其输出重定向到任何文本编写器。如果您实现了一个写入 Diagnostics.Debug 的文本编写器,则一切就绪。
Here's a textwriter that writes to the debugger.
这是一个写入调试器的文本编写器。
using System.Diagnostics;
using System.IO;
using System.Text;
namespace TestConsole
{
public class DebugTextWriter : TextWriter
{
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
//Required
public override void Write(char value)
{
Debug.Write(value);
}
//Added for efficiency
public override void Write(string value)
{
Debug.Write(value);
}
//Added for efficiency
public override void WriteLine(string value)
{
Debug.WriteLine(value);
}
}
}
Since it uses Diagnostics.Debug it will adhere to your compiler settings to wether it should write any output or not. This output can also be seen in Sysinternals DebugView.
由于它使用 Diagnostics.Debug,它将遵守您的编译器设置,以决定是否应该写入任何输出。此输出也可以在 Sysinternals DebugView 中看到。
Here's how you use it:
以下是您如何使用它:
using System;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
Console.SetOut(new DebugTextWriter());
Console.WriteLine("This text goes to the Visual Studio output window.");
}
}
}
If you want to see the output in Sysinternals DebugView when you are compiling in Release mode, you can use a TextWriter that writes to the OutputDebugString API. It could look like this:
如果要在发布模式下编译时在 Sysinternals DebugView 中看到输出,可以使用写入 OutputDebugString API 的 TextWriter。它可能看起来像这样:
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace TestConsole
{
public class OutputDebugStringTextWriter : TextWriter
{
[DllImport("kernel32.dll")]
static extern void OutputDebugString(string lpOutputString);
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
//Required
public override void Write(char value)
{
OutputDebugString(value.ToString());
}
//Added for efficiency
public override void Write(string value)
{
OutputDebugString(value);
}
//Added for efficiency
public override void WriteLine(string value)
{
OutputDebugString(value);
}
}
}
回答by AMissico
NullStream, which is defined as "A Stream with no backing store.". All the methods do nothing or return nothing. It is an internal class to Stream. The following code is taken from Microsoft's source code.
NullStream,定义为“没有后备存储的流”。所有的方法什么都不做或什么都不返回。它是一个内部类Stream。以下代码摘自微软的源代码。
Basically, when one of the Consolewrite methods is call the first time, a call is made to the Windows API function GetStdHandlefor "standard output". If no handle is returned a NullStreamis created and used.
基本上,当Console第一次调用其中一个写入方法时,会调用 Windows API 函数GetStdHandle以实现“标准输出”。如果没有返回句柄,则NullStream创建并使用一个。
Samuel's answer is correct and provides general information. To actually redirect Console output, regardless of the project type, use Console.SetOut(New System.IO.StreamWriter("C:\ConsoleOutput.txt")), which is a simple example.
塞缪尔的回答是正确的,并提供了一般信息。无论项目类型如何,要实际重定向控制台输出,请使用Console.SetOut(New System.IO.StreamWriter("C:\ConsoleOutput.txt")),这是一个简单的示例。
Directing Console, Debug, and Trace to File
将控制台、调试和跟踪定向到文件
To answer your question directly. Use the ConsoleTraceListenerand a StreamWriterto direct all three outputs to a file. I use the following for development only.
直接回答你的问题。使用ConsoleTraceListener和 aStreamWriter将所有三个输出定向到一个文件。我仅将以下内容用于开发。
Dim oLogFile As New System.IO.StreamWriter("C:\ConsoleOutput.txt")
oLogFile.AutoFlush = True 'so we do not have to worry about flushing before application exit
Console.SetOut(oLogFile)
'note, writing to debug and trace causes output on console, so you will get double output in log file
Dim oListener As New ConsoleTraceListener
Debug.Listeners.Add(oListener)
Trace.Listeners.Add(oListener)
NullStream
空流
[Serializable]
private sealed class NullStream : Stream {
internal NullStream() { }
public override bool CanRead {
get { return true; }
}
public override bool CanWrite {
get { return true; }
}
public override bool CanSeek {
get { return true; }
}
public override long Length {
get { return 0; }
}
public override long Position {
get { return 0; }
set { }
}
// No need to override Close
public override void Flush() {
}
public override int Read([In, Out] byte[] buffer, int offset, int count) {
return 0;
}
public override int ReadByte() {
return -1;
}
public override void Write(byte[] buffer, int offset, int count) {
}
public override void WriteByte(byte value) {
}
public override long Seek(long offset, SeekOrigin origin) {
return 0;
}
public override void SetLength(long length) {
}
}
回答by Samuel
Debug and Release do not control whether or not you get a console window. That is controlled by the project's output type. (Properties -> Application -> Output Type). Console Application will get you a console window which will visualize and receive input from the window into the Error, In, and Out streams in System.Console.
Debug 和 Release 不控制您是否获得控制台窗口。这是由项目的输出类型控制的。(属性 -> 应用程序 -> 输出类型)。控制台应用程序将为您提供一个控制台窗口,该窗口将可视化并从窗口接收输入到 System.Console 中的 Error、In 和 Out 流。
The System.Console class exposes several properties and methods for interacting with its streams even if you cannot see it. Most notably: Error, In, Out, SetError(), SetIn(), SetOut(), and the Read and Write methods.
System.Console 类公开了几个属性和方法,用于与其流交互,即使您看不到它。最值得注意的是:Error、In、Out、SetError()、SetIn()、SetOut() 以及 Read 和 Write 方法。
回答by Corey Byrum
The best solution for me was to change Console.WriteLine() to System.Diagnostics.Debug.WriteLine(). For example:
对我来说最好的解决方案是将 Console.WriteLine() 更改为 System.Diagnostics.Debug.WriteLine()。例如:
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
System.Diagnostics.Debug.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
Then you can view your errors as an object in the output window.
然后,您可以在输出窗口中将错误视为一个对象。
回答by rogerdpack
I'll actually second James on this one.
我实际上会在这个问题上第二个詹姆斯。
http://www.csharp411.com/console-output-from-winforms-application
http://www.csharp411.com/console-output-from-winforms-application
describes it in gross detail (if directing output to a file is enough though then you could easily use amissico's method). Most of the methods they describe mimic those described in http://dslweb.nwnexus.com/~ast/dload/guicon.htm
粗略地描述它(如果将输出定向到文件就足够了,那么您可以轻松使用 amissico 的方法)。他们描述的大多数方法都模仿了http://dslweb.nwnexus.com/~ast/dload/guicon.htm 中描述的方法
Changing your project to a "console" project would have a similar effect, as mentioned. Cheers!
如前所述,将您的项目更改为“控制台”项目会产生类似的效果。干杯!
回答by Remus Rusanu
Visual Studio launches Windows programs (/target:winexe) with the stdin/stdout/stderr redirectedto Named Pipes. The other end of each pipe is owned by the VS debugger and anything read on stderr/stdout is displayed in the Debug Output Window. Hence, Console.Writeauto-magically appears in the VS Debug output. Note that this does not happen if you attachto an already started process (since the redirect trick can only be done at process launch time).
Visual Studio 启动 Windows 程序 ( /target:winexe),并将 stdin/stdout/stderr重定向到命名管道。每个管道的另一端归 VS 调试器所有,在 stderr/stdout 上读取的任何内容都显示在调试输出窗口中。因此,Console.Write自动神奇地出现在 VS 调试输出中。请注意,如果您附加到已启动的进程,则不会发生这种情况(因为重定向技巧只能在进程启动时完成)。
When launching console programs (/target:exe) this redirect does not occur so the Console.Writegoes tothe actual console (or wherever the stdoutis redirected).
启动控制台程序 ( /target:exe) 时,不会发生此重定向,因此Console.Write会转到实际控制台(或stdout重定向的任何地方)。
I couldn't find anything that documents this behavior, is just my conclusion from investigating how VS launches and debugs apps.
我找不到任何记录此行为的内容,这只是我调查 VS 如何启动和调试应用程序的结论。
回答by chills42
It goes to the console (standard output) or to the stream that the console is set to.
它转到控制台(标准输出)或控制台设置的流。
回答by s3c
As already commented on OP's question:
正如已经评论过 OP 的问题:
No need to write additional code
无需编写额外的代码
In Visual Studio uppermost menu choose
在 Visual Studio 最上面的菜单中选择
Debug > Windows > Output
调试 > 窗口 > 输出
The output windows will only be visible in debug mode and it will show all e.g.
Console.WriteLine("Debug MyVariable: " + MyVariable)when you get to them.
输出窗口仅在调试模式下可见,并且会Console.WriteLine("Debug MyVariable: " + MyVariable)在您到达它们时显示所有内容
。
Set a breakpoint before (click the different-coloured empty area before the line number at the start of a chosen line), debug (F5), and then step through code line by line (F11) until you do.
在之前设置断点(单击所选行开头的行号之前的不同颜色的空白区域),调试(F5),然后逐行执行代码(F11),直到完成。
回答by James Curran
Even in a WinForms app, you can create a console window, but you'll have to go through P/Invoke to call a Win32 method directly. See http://pinvoke.net/default.aspx/kernel32/AllocConsole.html
即使在 WinForms 应用程序中,您也可以创建控制台窗口,但您必须通过 P/Invoke 直接调用 Win32 方法。见http://pinvoke.net/default.aspx/kernel32/AllocConsole.html
回答by Joel Coehoorn
Console.writeline() goes to a console window: the black command / dos prompt.
Console.writeline() 进入控制台窗口:黑色命令/dos 提示符。

