canterlot
canterlot

Reputation: 19

read a file letter by letter in c#

I am trying to read a file letter by letter however my various attempts do not work and continue to find only one time my letter in the file

string lettre = "T";
string[] file = File.ReadAllLines("C:/<pathto>/test7.txt");

for (int i = 0; i < file.Length;i++)
{
    if (file[i].Contains(lettre))
    {
        Console.WriteLine("test");
    }
}

I try to read the file letter by letter to generate pixels but I block on reading the file

Upvotes: 0

Views: 1174

Answers (2)

Francisco Card&#227;o
Francisco Card&#227;o

Reputation: 11

This should work:

using System;
using System.IO;
using System.Text;

namespace Exemple
{
    class Program
    {
        static void Main(string[] args)
        {
            char lettre = 'T';

            using(StreamReader file = new StreamReader(@"C:\<pathto>\test7.txt", Encoding.UTF8)) //you can change the Encoding file type
            {
                while (!file.EndOfStream)
                {
                    string line = file.ReadLine();
                    foreach(char letter in line)
                    {
                        if(letter == lettre)
                            Console.WriteLine("An letter " + lettre + " founded.");
                    }
                }
            }
        }
    }
}

Also take care on your OS, if is Windows the path separator is the '\', if is a Unix OS is the '/'.

Upvotes: 1

Thomas Weller
Thomas Weller

Reputation: 59258

From your code it looks as if it's fine for you to read the whole file into memory. If so, it's just a matter of looping.

Also note the difference between the string "T" and the character (letter) 'T'.

string[] file = File.ReadAllLines("C:/<pathto>/test7.txt");

foreach(string line in file)
{
    foreach(char letter in line)
    {
         if (letter == 'T')
         {
                // do something
         }
    }
}

If you really want to read the file character by character, it's also fine if the characters are from ASCII range only. You can use FileStream.ReadByte()

using(var fileStream = new FileStream(fileName, FileMode.Open))
{
    int character = 0;
    while(character != -1)
    {
         character = fileStream.ReadByte();
         if (character == -1) continue;
         if ((char)character == 'T')
         {
              // do something
         }
    }
}

Upvotes: 1

Related Questions