如何从读取文件及其中的新内容中检索的文本中写入新文件

时间:2019-04-15 06:40:26

标签: c#

我正在阅读的文本有几行。 我想向其中添加新行,例如日期,费用,介绍。 我想我可以手动输入它,但是我想知道是否可以读取每一行并将其与新输入一起打印到新文件中,并在单独的行上。我仍然想使用流阅读器和流作家,因为这似乎是我在网上可以找到的最简单的一种。 看起来唯一可以打印的是:System.IO.StreamReader

        //WRITE FILE
        public void writeFile()
        {

            GroceryItem readGroceryList = new GroceryItem();

            string[] lines = { "Grocery for you", Convert.ToString(DateTime.Now), readFile()  };
            StreamWriter file = new StreamWriter("c:\\MicrosoftVisual\\invoice.txt");
            foreach (string line in lines)
            {
                file.WriteLine(line);
                file.Flush();
            }
        }

        public string readFile() // to adjust name of method later if require
        {
            //READ FILE
            StreamReader myReader = new StreamReader("groceries.txt");
            string consoleLine = "";
            while (consoleLine != null)
            {
                consoleLine = myReader.ReadLine();
                if (consoleLine != null)
                {
                    return Convert.ToString(myReader);
                }
            }
            return consoleLine;
        }

        public GroceryItem (string n, double p)

1 个答案:

答案 0 :(得分:0)

您的主要问题在于readFile方法。我认为您的意图是读取所有行而不是仅一行,然后将您的阅读器作为字符串返回。为此,我将收集List<string>中的所有行并将其返回,就像这样:

public List<string> ReadFile()
{
    StreamReader myReader = new StreamReader("groceries.txt");
    List<string> list = new List<string>(); // Create an empty list of strings
    while (myReader.Peek() >= 0) // Checks if the stream has reacht the end of the file.
    {
        list.Add(myReader.ReadLine()); // Reads a line out of the files and appends it to the list.
    }
    return list; // Returns the list from the method.
}

通过这些更改,您还需要调整writeFile方法,如下所示:

public void WriteFile()
{
    List<string> lines = ReadFile();
    // Calls ReadFile to get the already exsisting lines from the file.
    lines.Add("Grocery for you"); // You can add new lines now.
    lines.Add(DateTime.Now.ToString());
    StreamWriter file = new StreamWriter("c:\\MicrosoftVisual\\invoice.txt");
    foreach (string line in lines)
    {
        file.WriteLine(line);
    }
    file.Flush(); // You only need to call Flush once when you are finished writing to the Stream.
}

通过使用C#的Stream帮助程序类,甚至有一个更简单的不带File的变体。

List<string> lines = new List<string>(File.ReadAllLines("groceries.txt"));
// Reads all lines from the file and puts them into the list.
lines.Add("Grocery for you"); // You can add new lines now.
lines.Add(DateTime.Now.ToString());
File.WriteAllLines("c:\\MicrosoftVisual\\invoice.txt", lines);