我正在阅读的文本有几行。 我想添加新行,例如日期、成本、介绍。 我想我可以手动输入它,但我想知道是否可以读取每一行并将其与新输入一起打印到新文件中。仍然想使用流阅读器和流编写器,因为它似乎是我能在网上找到的最简单的一个。 它似乎打印的唯一内容是: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)
您的主要问题在于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# 的File
帮助程序类,甚至还有一个更简单的变体,无需Stream
s。
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);