zsx's Old Blog

黑历史逐步隐藏中_(:з」∠)_仅保留部分可能有些价值的文章,并不保证将来的可访问性。

解决Console.WriteLine句柄无效问题

QQ截图20131130184242

 

写程序写蛋疼了,先FreeConsole再AllocConsole。  这个时候就会出现句柄无效问题。

未处理System.IO.IOException
  Message=句柄无效。

  Source=mscorlib
  StackTrace:
       在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       在 System.IO.__ConsoleStream.Write(Byte[] buffer, Int32 offset, Int32 count)
       在 System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
       在 System.IO.TextWriter.SyncTextWriter.Write(String value)

看看这个错误信息。System.IO.StreamWriter,貌似懂得了什么。

 

Now, google it!

 

在这个StackOverFlow问答里,介绍了Console.WriteLine的实现原理,以及给出了一个重新让它输出到Console的方法“Console.OpenStandardOutput”

http://stackoverflow.com/questions/7537279/calling-console-writeline-before-allocating-the-console

The first time you use Console.WriteLine, the Console class creates a TextWriter and associates it with the Console.Out property. The way it does this is to use Win32 to open the low-level file handle associated with the standard output file handle. If the standard output handle is invalid, Console.Out is set to TextWriter.Null, which discards all output.

The Win32 AllocConsole function, creates and sets the standard output handle so after calling it the standard output handle is either different or now valid. In either case, Console.Out has already been set either to use the old standard output or to discard all output.

To force a re-open of Console.Out after calling AllocConsole, you can use this method:

Console.OpenStandardOutput

——Rick Sladkey

Then, MSDN it!

 

MSDN(http://msdn.microsoft.com/en-us/library/16f09842.aspx)直接给出了示例代码 :

        // Recover the standard output stream so that a  

        
// completion message can be displayed.

        StreamWriter standardOutput = 
new
 StreamWriter(Console.OpenStandardOutput());
        standardOutput.AutoFlush = 
true
;
        Console.SetOut(standardOutput);
        Console.WriteLine(
"INSERTTABS has completed the processing of {0}."
, args[0]);

 

很好,照搬过来。不出错了。但是输出中文时……

QQ截图20131130185628

 

那就再读读MSDN!

最终,问题落在

                StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());

已知StreamWriter可以设置编码,那就

                StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput,System.Text.Encoding.Default);

吧!

 

于是最终的代码就是:

                AllocConsole();

                StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput(),System.Text.Encoding.Default);

                standardOutput.AutoFlush = true;

                Console.SetOut(standardOutput);

 

控制面板
您好,欢迎到访网站!
  查看权限
Google Adsense
文章归档
站点信息
  • 文章总数:259
  • 页面总数:10
  • 分类总数:17
  • 标签总数:136
  • 评论总数:1644
  • 浏览总数:216659

Powered By Z-BlogPHP 1.5.1 Zero

闽ICP备15006942号   闽公网安备 35010302000147号