user3548593
user3548593

Reputation: 499

Merge Files in a directory c#

I have many text files in a directory and I need to merge them into one

I tried the following code

File.WriteAllLines(
    outputFileName,
    Directory.GetFiles(directory, "*.txt")
        .SelectMany(f =>
            File.ReadLines(f).Concat(new[] { Environment.NewLine })));

It works fine but my problem is that I get empty blank lines between the content of each file . Is there a way to modify it in order to get a text file without those empty lines ?

Upvotes: 1

Views: 605

Answers (3)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73452

Converting my comment as an answer on request.

It seems you're concatenating Environment.NewLine at end of each file, which adds the new line between the content of each file. If that's not what you need why do you use that statement?

Removing Concat(new[] { Environment.NewLine }) should yield the expected result.

var allLines = Directory.GetFiles(directory, "*.txt")
                        .SelectMany(f => File.ReadLines(f));
File.WriteAllLines(outputFileName, allLines);

Upvotes: 2

Mattias Åslund
Mattias Åslund

Reputation: 3907

Replace Environment.NewLine with String.Empty

Upvotes: 3

Nayeem Mansoori
Nayeem Mansoori

Reputation: 831

Please try this code :

string[] txtFiles;
        txtFiles = Directory.GetFiles(txtFileDestination.Text, "*.txt");
        using (StreamWriter writer = new StreamWriter(txtFileDestination.Text + @"\allfiles.txt"))
        {
            for (int i = 0; i < txtFiles.Length; i++)
            {
                using (StreamReader reader = File.OpenText(txtFiles[i]))
                {
                    writer.Write(reader.ReadToEnd());
                }
            }
        }

Upvotes: 0

Related Questions