如何在文件中写一个字符串,中间有换行符?

时间:2013-10-09 13:01:26

标签: c# c#-4.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.......

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

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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);
}

应该这样做。

答案 2 :(得分: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);
}