简体   繁体   中英

Count line in a file and write the count into a new file using same name of the text in the folder

I'm trying to write code to count the lines in each file inside my folder( NewCode ), and I have that part working, but I also need to write the line count into a new file (in a new folder ( NewCodeOutput )) with the same name as the text file that was read.

Here's my code:

string[] ori_Files = Directory.GetFiles(@"D:\C#\NewCode\", "*.txt*", 
    SearchOption.TopDirectoryOnly);

string path2 = @"D:\C#\NewCodeOutput\";

foreach (var file in ori_Files)
{
    using (StreamReader file1 = new StreamReader(file))
    {
        string line;
        int count = 0;

        while ((line = file1.ReadLine()) != null)
        {
            //Console.WriteLine(line);
            count++;
        }

        Console.WriteLine(count);
    }
}

Console.ReadLine();

You can use Path.GetFileName to extract the file name, and then write the count.

var completeOutputPath = Path.Combine(path2,Path.GetFileName(file));
File.WriteAllText(completeOutputPath, $"Count:{count}");

This should appear before your Console.WriteLine(count) within the loop

You can simply use Path.Combine along with Path.GetFileName to generate the new path with the existing file's name.

You can also use the System.IO.File class to simplify the line counting and file writing:

foreach (var file in Directory.GetFiles(@"D:\C#\NewCode\", "*.txt*",
    SearchOption.TopDirectoryOnly))
{
    File.WriteAllText(Path.Combine(@"D:\C#\NewCodeOutput\", Path.GetFileName(file)),
        File.ReadAllLines(file).Length.ToString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM