[英]Making ASCII with C#?
我需要为我的家庭作业做一些艺术品。 给定的是一个字节数组,我需要将其显示为 7 行,每行 11 个字符,但我真的不知道如何构造它,此外,我正在收到一个 System.IO.EndOfStreamExeption(它连接到而部分)。 最后,我很确定它应该在控制台上显示“C#”。
internal class Program
{
public void ESAIn(string Path)
{
byte[] array = { 32, 32, 67, 67, 32, 32, 32, 35, 32, 35, 32,
32, 67, 32, 32, 67, 32, 32, 35, 32, 35, 32,
67, 32, 32, 32, 32, 32, 35, 35, 35, 35, 35,
67, 32, 32, 32, 32, 32, 32, 35, 32, 35, 32,
67, 32, 32, 32, 32, 32, 35, 35, 35, 35, 35,
32, 67, 32, 32, 67, 32, 32, 35, 32, 35, 32,
32, 32, 67, 67, 32, 32, 32, 35, 32, 35, 32 };
FileStream stream = File.Open(Path, FileMode.Truncate, FileAccess.ReadWrite);
stream.Write(array, 0, array.Length);
stream.Close();
}
public void ESAOut(string Path)
{
BinaryReader reader = new BinaryReader(File.Open(Path, FileMode.Open));
var count = 0;
int b;
while ((b = reader.ReadByte()) > -1)
{
Console.Write((char)b);
if (count > 0 && (++count % 11) == 0)
{
Console.WriteLine();
}
}
}
如果您只想将byte[]
保存到文件中,请调用File.WriteAllBytes
byte[] array = ...
File.WriteAllBytes("myFile.dat", array);
但是您似乎想将每11
个字节转换为一个string
,然后才将这些字符串保存到一个文件中。 我们可以通过quering做array
使用LINQ的帮助:
using System.IO;
using System.Linq;
...
byte[] array = ...
var lines = array
.Select((value, index) => new { value, index })
.GroupBy(pair => pair.index / 11, pair => pair.value)
.Select(group => string.Concat(group.Select(b => (char)b)));
File.WriteAllLines("myFile.txt", lines);
现在myFile.txt
包含
CC # #
C C # #
C #####
C # #
C #####
C C # #
CC # #
编辑:如果您想按原样存储array
:
File.WriteAllBytes("myFile.dat", array);
要加载文件并显示艺术作品,您可以使用File.ReadAllBytes
获取byte[]
,然后使用Linq获取文本表示:
string art = string.Join(Environment.NewLine, File
.ReadAllBytes("myFile.dat")
.Select((value, index) => new { value, index })
.GroupBy(pair => pair.index / 11, pair => pair.value)
.Select(group => string.Concat(group.Select(b => (char)b)))
);
Console.Write(art);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.