Reputation: 233
what i am trying to do is to read the file a.txt and output each character in a single line i am having a real difficulty to solve this problem any help will be really appreciated.if you write the code please comment so i can understand more clearly as i am beginner.thanks
namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
using (StreamReader r = new StreamReader("a.txt"))
{
string @char;
while((@char = r.ReadBlock() != null))
foreach(char i in @char)
{
Console.WriteLine(i);
}
}
}
}
}
Upvotes: 3
Views: 14845
Reputation: 1062640
i want to read the file and output all the file char by char , each char in new line
OK; there's a lot of ways to do that; the simplest would be (for small files):
string body = File.ReadAllText("a.txt");
foreach (char c in body) Console.WriteLine(c);
To use ReadBlock
to handle the file in chunks (not lines):
using (StreamReader r = new StreamReader("a.txt"))
{
char[] buffer = new char[1024];
int read;
while ((read = r.ReadBlock(buffer, 0, buffer.Length)) > 0)
{
for (int i = 0; i < read; i++)
Console.WriteLine(buffer[i]);
}
}
This reads blocks of up to 1024 characters at a time, then writes out whatever we read, each character on a new line. The variable read
tells us how many characters we read on that iteration; the read > 0
test (hidden slightly, but it is there) asks "have we reached the end of the file?" - as ReadBlock
will return 0 at the end.
Upvotes: 10