Pickled Egg
Pickled Egg

Reputation: 123

How can I write a strings to file with linebreaks inbetween?

I want to be able to write some values to a file whilst creating blank lines in between. Here is the code that I have so far:

TextWriter w_Test = new StreamWriter(file_test);
foreach (string results in searchResults)
{
    w_Test.WriteLine(Path.GetFileNameWithoutExtension(results));
    var list1 = File.ReadAllLines(results).Skip(10);
    foreach (string listResult in list1)
    {
        w_Test.WriteLine(listResult);
    }
}
w_Test.Close();

This creates 'Test' with the following output:

result1
listResult1
listResult2
result2
listResult3
result3
result4

I want to write the results so that each result block is 21 lines in size before writing the next, e.g.

result1
(20 lines even if no 'listResult' found)
result2
(20 lines even if no 'listResult' found)
etc.......

What would be the best way of doing this??

Upvotes: 0

Views: 81

Answers (3)

Tony Vitabile
Tony Vitabile

Reputation: 8594

TextWriter w_Test = new StreamWriter(file_test);
foreach (string results in searchResults)
{
    int noLinesOutput = 0;
    w_Test.WriteLine(Path.GetFileNameWithoutExtension(results));
    noLinesOutput++;
    var list1 = File.ReadAllLines(results).Skip(10);
    foreach (string listResult in list1)
    {
        w_Test.WriteLine(listResult);
        noLinesOutput++;
    }
    for ( int i = 20; i > noLinesOutput; i-- )
        w_Test.WriteLine();
}
w_Test.Close();

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460098

Perhaps with this loop:

var lines = 20;
foreach(string fullPath in searchResults)
{
    List<string> allLines = new List<string>();
    allLines.Add(Path.GetFileNameWithoutExtension(fullPath));
    int currentLine = 0;
    foreach(string line in File.ReadLines(fullPath).Skip(10))
    {
        if(++currentLine > lines) break;
        allLines.Add(line);
    }
    while (currentLine++ < lines)
        allLines.Add(String.Empty);
    File.WriteAllLines(fullPath, allLines);
}

Upvotes: 0

staafl
staafl

Reputation: 3225

Here's a simple helper method I use in such cases:

// pad the sequence with 'elem' until it's 'count' elements long
static IEnumerable<T> PadRight<T>(IEnumerable<T> enm,
    T elem,
    int count)
{
    int ii = 0;
    foreach(var elem in enm)
    {
        yield return elem;
        ii += 1;
    }
    for (; ii < count; ++ii)
    {
        yield return elem;
    }
}

Then

foreach (string listResult in 
    PadRight(list1, "", 20))
{
    w_Test.WriteLine(listResult);
}

should do the trick.

Upvotes: 0

Related Questions