Link to home
Start Free TrialLog in
Avatar of gateguard
gateguard

asked on

concatenate 5 files dropping blank lines, using c# dot net

Using Visual Studio 2013 c# project.

I want to read 5 text files into a single file skipping over blank lines in the 5 input files.

What's the best way of doing this.

I would like to use streamWriter but I can't see a way to append.

But any other way is fine with me as long as it works.

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of ktaczala
ktaczala
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gateguard
gateguard

ASKER

So this writes to a new file:

new StreamWriter("c:\\file.txt");

And this appends to an existing file:

new StreamWriter("c:\\file.txt", true);

?

Thanks.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks to both of you.
Hi gateguard;

A little late but have a look at this.

using System.IO;
using System.Text.RegularExpressions;

// Get the file names that are going to be appended
DirectoryInfo dir = new DirectoryInfo("C:/Working Directory/");
List<string> fnames = dir.GetFiles("file?.txt").Select(f => f.FullName).ToList();

// String to hold appended text
String fileText = "";

// Read and append data
foreach(string fn in fnames)
{
    string ft = File.ReadAllText(fn).Trim() + "\r\n";
    fileText += ft;
}

// Remove all blank line
fileText = Regex.Replace(fileText, "(\r\n){2,}", "\r\n");

// Create a StreamWriter
StreamWriter sw = new StreamWriter("C:/Working Directory/filesAppended.txt");
// Write the data out
sw.Write(fileText);
// Close the file.
sw.Close();

Open in new window