[英]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'
.还要注意字符串
"T"
和字符(字母) '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.如果您真的想逐个字符地读取文件,如果字符仅来自 ASCII 范围也可以。 You can use FileStream.ReadByte()
您可以使用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 '/'.还要注意您的操作系统,如果是 Windows,路径分隔符是“\\”,如果是 Unix 操作系统,则路径分隔符是“/”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.