简体   繁体   中英

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

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
         }
    }
}

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 '/'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM