I need to do some kind of an artwork for my homework. Given is an byte array, which I need to be displayed as 7 lines with 11 characters each line but I really can't find out how to structure it, also, I'm recieving a System.IO.EndOfStreamExeption (which connects to the while part). In the end, I'm pretty sure it's supposed to display "C#" on the console.
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();
}
}
}
CodePudding user response:
If you want just to save the byte[]
into a file, call File.WriteAllBytes
byte[] array = ...
File.WriteAllBytes("myFile.dat", array);
But you seem to want to convert every 11
bytes into a string
and only then save these strings into a file. We can do it by quering array
with a help of 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);
Now myFile.txt
contains
CC # #
C C # #
C #####
C # #
C #####
C C # #
CC # #
Edit: If you want store array
as it is:
File.WriteAllBytes("myFile.dat", array);
To load the file and display the art you can use File.ReadAllBytes
to get byte[]
and then Linq to have a text representation:
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);