如何在c#中逐行读取文本文件,并将偶数编号行保存为**even.txt**,奇数编号行保存为**odd.txt**

本文关键字:编号 保存 txt even odd 逐行 读取 文件 取文本 | 更新日期: 2023-09-27 18:17:47

如何在c#中逐行读取文本文件,并将偶数编号行保存到even.txt,将奇数编号行保存到odd.txt ?

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

如何在c#中逐行读取文本文件,并将偶数编号行保存为**even.txt**,奇数编号行保存为**odd.txt**

不要在循环中打开/关闭输出文件,您可以这样做…

using (var odd = File.CreateText("odd.txt"))
using (var even = File.CreateText("even.txt"))
{
    int count = 0;
    foreach (var line in File.ReadLines(filename))
    {
        (count++ % 2 == 0 ? even : odd).WriteLine(line);
    }
}

你想要的是这样的:

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