0

我希望能够将一些值写入文件,同时在其间创建空行。这是我到目前为止的代码:

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();

这将创建'Test'以下输出:

result1
listResult1
listResult2
result2
listResult3
result3
result4

我想编写结果,以便在编写下一个结果块之前每个结果块的大小为 21 行,例如

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

这样做的最佳方法是什么?

4

3 回答 3

1
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();
于 2013-10-09T13:07:27.710 回答
0

这是我在这种情况下使用的一个简单的辅助方法:

// 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;
    }
}

然后

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

应该做的伎俩。

于 2013-10-09T13:08:31.257 回答
0

也许有了这个循环:

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);
}
于 2013-10-09T13:16:31.583 回答