简体   繁体   English

C#向/从控制台读取/写入字节

[英]c# reading/writing bytes to/from console

I have a byte[] array and want to write it to stdout: Console.Out.Write(arr2str(arr)) . 我有一个byte[]数组,想将其写入stdout: Console.Out.Write(arr2str(arr)) How to convert byte[] to string, so that app.exe > arr.txt does the expected thing? 如何将byte[]转换为字符串,以便app.exe > arr.txt可以完成预期的工作? I just want to save the array to a file using a pipe, but encodings mess things up. 我只想使用管道将数组保存到文件中,但是编码使事情搞砸了。

I'd later want to read that byte array from stdin: app.exe < arr.txt and get the same thing. 稍后,我想从stdin中读取该字节数组: app.exe < arr.txt并得到相同的结果。

How can I do these two things: write and read byte arrays to/from stdin/stdout? 我该如何做这两件事:向/从stdin / stdout写入和读取字节数组?

EDIT: 编辑:

I'm reading with string s = Console.In.ReadToEnd() , and then System.Text.Encoding.Default.GetBytes(s) . 我正在使用string s = Console.In.ReadToEnd() ,然后使用System.Text.Encoding.Default.GetBytes(s) I'm converting from array to string with System.Text.Encoding.Default.GetString(bytes) , but this doesn't work when used with < , > . 我正在使用System.Text.Encoding.Default.GetString(bytes)从数组转换为字符串,但是当与<>一起使用时,这不起作用。 By "doesn't work" I mean that writing and reading over a pipe does not return the same thing. “无效”是指在管道上进行写入和读取不会返回相同的结果。

To work with binary files you want Console.OpenStandardInput() to retrieve a Stream that you can read from. 要使用二进制文件,您希望Console.OpenStandardInput()检索您可以读取的Stream。 This has been covered in other threads here at SO, this one for example: Read binary data from Console.In SO的其他线程对此进行了介绍,例如: 从Console.In读取二进制数据。

If you are writing to Console.WriteLine you need to encode the text in to a printable format. 如果要写入Console.WriteLine,则需要将文本编码为可打印的格式。 If you want to output to a file as a binary you can't use Console.WriteLine 如果要输出为二进制文件, 则不能使用Console.WriteLine

If you still need to output to the console you either need to open the raw stream with Console.OpenStandardOutput() or call Convert.ToBase64String to turn the byte array to a string. 如果仍然需要输出到控制台,则需要使用Console.OpenStandardOutput()打开原始流,或者调用Convert.ToBase64String将字节数组转换为字符串。 There is also Convert.FromBase64String to come back from base64 to a byte array. 还有Convert.FromBase64String可以从base64返回到字节数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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