如何在C#控制台应用程序中将数据写入文本文件而不覆盖当前数据

时间:2017-08-08 05:18:36

标签: c# console-application

我需要C#控制台应用程序中的代码,在应用程序运行时保存输出数据,并且不会覆盖以前的数据并逐行保存

3 个答案:

答案 0 :(得分:1)

您可以使用文件:

 List<string> lists = new List<string> {"111","222","333" };
  File.AppendAllLines("test.txt",lists);

如果你有字符串列表,你也可以在一行中完成。

package main

import (
    "bufio"
    "os"
    "fmt"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    var text string
    fmt.Print("Enter your text: ")
    scanner.Scan()
    text = scanner.Text()
    fmt.Println("Your text was: ", text)
}

答案 1 :(得分:0)

using (System.IO.StreamWriter file = 
            new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
        {
            foreach (string line in lines)
            {
                // If the line doesn't contain the word 'Second', write the line to the file.
                if (!line.Contains("Second"))
                {
                    file.WriteLine(line);
                }
            }

答案 2 :(得分:0)

您必须使用StreamWriter类重载构造函数: using (StreamWriter output = new StreamWriter(pathToFile, true)), 第二个布尔参数表示文件是否应附加(true)或覆盖(false)。