Venkatesh Venkatesh - 18 days ago 7
C# Question

Detailed picture about StreamReader and StreamWriter

How to read the text file line by line and save even numbering lines to even.txt and odd numbering lines to odd.txt in c# ?

StreamReader dr=new StreamReader(@"C:\Users\Venkatesh\Desktop\sample.txt");
string ln=string.Empty;
int c = 0;
while (ln != null)
{
c += 1;
if (c%2 == 0){
StreamWriter even = new StreamWriter(@"C:\even.txt");
even.WriteLine(ln);
}
else {
StreamWriter odd = new StreamWriter(@"C:\odd.txt");
odd.WriteLine(ln);
}
}

Answer

What you want is something like this:

string ln = string.Empty;
int c = 0;

using (StreamWriter odd = new StreamWriter(@"C:\Users\rdaniel\Desktop\odd.txt"))
using (StreamWriter even = new StreamWriter(@"C:\Users\rdaniel\Desktop\even.txt"))
using (StreamReader dr = new StreamReader(@"C:\Users\rdaniel\Desktop\example.txt"))
{
    while (ln != null)
    {
        ln = dr.ReadLine();
        c += 1;
        if (c % 2 == 0)
        {
            even.WriteLine(ln);
        }
        else
        {
            odd.WriteLine(ln);
        }
    }
}
Comments