Search code examples
c#iofilestream

C# Beginner File Reading


Okay I searched for an answer to this but couldn't find it.

here's the code:

     FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

        byte[] fileText = new byte[fs.Length];

        int bytesRead = fs.Read(fileText, 0, fileText.Length);

        Console.WriteLine(Encoding.ASCII.GetString(fileText, 0, bytesRead));

Let me get this straight,

  1. We declare a filestream
  2. We Declare a byte array.. and set its CAPACITY to fs.Length
  3. ???? Why does fs.Read() return an INTEGER ???
  4. ??? How does this line display the text from the .txt file to the console? we passed in the byte[] in the getstring() method, but isnt that byte[] empty? we only set its capacity to fs.length? where did the reading happen and how?

TIA


Solution

  • If you are trying to read a text file and display all it's lines in console

    foreach(string line in File.ReadAllLines("YourFilePath"))
    {
        Console.WriteLine(line);
    }
    

    In your method

    FileStream fs = new FileStream("YourFilePath", FileMode.Open, FileAccess.Read);
    

    Opens the file for reading into stream fs.

    byte[] fileText = new byte[fs.Length];
    

    Gets the number of bytes in the file content, and creates a byte array of that size

    int bytesRead = fs.Read(fileText, 0, fileText.Length);
    

    Reads the byte content, from 0 to end of content (we have length from last statement), i.e. the complete contents into the array you created. So, now your byte array fileText has all the byte contents from the file.

    It returns the number of bytes read in this operation, if you need that for some reason. This can be <= the number of bytes you wanted to read (less if less bytes were available in the file content). In your case, it will be same as fileText.Length since you already calculated that.

    System.Console.WriteLine(Encoding.ASCII.GetString(fileText, 0, bytesRead));
    

    Converts the byte array into ASCII encoded text and writes to console.