Hi guys,
I am trying to read a text file, filter out the tabs and replace them with commas. For some reason my code will just not do this!! I am new to this site and still doing my degree so still novice programmer. Many thanks
Printable View
Hi guys,
I am trying to read a text file, filter out the tabs and replace them with commas. For some reason my code will just not do this!! I am new to this site and still doing my degree so still novice programmer. Many thanks
Below is the function in which the text file is being read -
private void Convert()
{
StreamReader sr = new StreamReader(ofd1.FileName);
StreamWriter sw = new StreamWriter(sfd1.FileName);
string line = "";
char c;
while((line = sr.ReadLine()) != null)
{
c = (char)sr.Read();
if (c == '\t')
{
//MessageBox.Show("char found");
c = ',';
sw.Write(c);
sw.Flush();
}
sw.WriteLine(line);
}
sr.Close();
sw.Close();
MessageBox.Show("Convertion complete");
}
You might want to try reading in using a BinaryReader and writing out using BinaryWriter.
BinaryReader r = new BinaryReader(fs);
binWriter = new BinaryWriter(File.Open(outfilename, FileMode.Create));
binWriter.Write(input_char);
Code:int t
while((t = sr.Read()) > -1)
{
c = (char)t;
if (c == '\t')
{
Why would you read a text file using a BinaryReader? If you're comparing characters you need to be encoding aware which means you need to convert the raw bytes into a character using either a StreamReader with the correct encoding set or by reading into a byte[] and using the System.Text.Encoding classes to do it. The former is by far the easiest.
Cheers for you help there was no need for a binary reader, i recieved no emals saying my forum had been responded to so I ended up sorting it myself cheers for your help Silent Sojourner your answer was similar to mine except i used peek i ended up with -
while((sr.Peek() >= 0))
{
char c = (char)sr.Read();
if (c == '\t')
{
c = ',';
}
sw.Write((char)c); //rewrite all characters
}
Reading and writing one character at a time would be the slowest possible way to do this. I would read the entire file at once into a string then use replace to replace all the tabs with commas then write the resulting string to disk all at once. Should be at least 100 times faster.
well it depends. what if the file size is huge, say, 2gb?
If it were that big then reading all at once would be a lot faster still. Most systems today have at least 4 gigs of ram and ram is much faster than disk and a single read is much faster than 1000s of reads.
I understand how reading and writing it character by character could be a bit naff in some circimstances. But the aim of this program was to demonstrate the use of threads and by reading a large text file by character demonstrated that we needed another thread. cheers