Search code examples
c#filestream

filestream read array to lines C#


i'm veeeery new to this. I'm supposed to write a file with an array (got that) and read the content in 7 lines, 11 bytes each (no idea how).

In case you speak german, thats my assignment: Die Konsolenausgabe soll in sieben Zeilen mit jeweils elf Zeichen gegliedert werden – dies entspricht auch der vorstehenden Anordnung der Array-Elemente. Beachten Sie aber, dass eine Zeile im Array aus 33 Zeichen besteht – Ihre Konsolenausgabe soll hingegen elf Zeichen umfassen!

here's what i have so far:

using System;
using System.IO;

namespace ESA_2
{
    class Program
    {
        public void ESA2In(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(@"C:\users\...test.txt", FileMode.Create);
            stream.Write(array, 0, array.Length);
            stream.Close();
        }

        public void ESA2Out(string Path)
        {
            StreamReader reader = new StreamReader(File.Open(@"C:\users\...test.txt", FileMode.Open));
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
            Console.WriteLine();
            reader.Close();
        }

        static void Main(string[] args)
        {
            string Path = @"C:\users\...\test.txt";

            Program test = new Program();

            test.ESA2In(Path);
            test.ESA2Out(Path);
        }
    }
}

Solution

  • You can read your symbols back as string using Read() method. For example,

    public void ESA2Out(string Path)
    {
      using (var reader = new StreamReader(File.Open(@"C:\users\...test.txt", FileMode.Open)))
      {
        for (var lineNumber = 0; lineNumber < 7; lineNumber++)
        {
          string line = "";
          for (var charNumber = 0; charNumber < 11; charNumber++)
            line = line + (char)reader.Read();
          Console.WriteLine(line);
        }
        Console.WriteLine();
        reader.Close();
      }
    }
    

    BTW, it should print big 'C#', where 'C' is made out of 'C'-letter, and '#' of '#'-s.