c#中,怎样逐行读取.txt里面的字符,统计出现的次数,并保存到另一个.txt文件里

2025-01-31 00:35:06
推荐回答(1个)
回答1:

using System;
using System.IO;

class Test
{

    public static void Main()
    {
        string path = @"D:\1.txt"; //txt文件的路径
        try
        {
            if (File.Exists(path)) //文件必须存在
            {
                using (StreamReader sr = new StreamReader(path)) //StreamReader读取文件流
                {
                    string desPath = @"D:\1_New.txt";
                    using (StreamWriter sw = new StreamWriter(desPath)) //StreamWriter写入文件流
                    {
                        while (sr.Peek() >= 0) //对应行有内容才继续
                        {
                            sw.WriteLine(sr.ReadLine()); //写入读取的每行内容
                        }
                    }
                }

                Console.WriteLine("Work done.");
            }
            else
            {
                Console.WriteLine("File NOT exists.");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }

        Console.ReadKey();
    }
}