早上好
我想咨询一下如何使用 C# 从文本文件中读取列表并将信息保存到列表(数组)中。
这是一个小练习,我将信息写入文本文件,现在我想读取信息并将其保存到不同的数组中。
string name;
string selection;
FileStream fs = new FileStream("C:/Documents and Settings/Arian/Desktop/Perl (PERLC-09)/bookExamples/unitThree/menuLunch.txt", FileMode.Create, FileAccess.ReadWrite);
BufferedStream bs = new BufferedStream(fs);
fs.Close();
StreamWriter sw = new StreamWriter("C:/Documents and Settings/Arian/Desktop/Perl (PERLC-09)/bookExamples/unitThree/menuLunch.txt");
Console.WriteLine("writing the menu");
string[]menu = new string[]{"burger", "steak", "sandwich", "apple", "soup", "pasta", "pizza"};
for (int i = 0; i < menu.Length; i++)
{
sw.WriteLine(menu[i]);
}
sw.Close();
Console.WriteLine("Thanks for creating the menu, could you please tell me your name? ");
name = Console.ReadLine();
Console.WriteLine("hallo " + name + " Please make your selection from the menu");
FileStream fsream = new FileStream("C:/Documents and Settings/Arian/Desktop/Perl (PERLC-09)/bookExamples/unitThree/menuLunch.txt", FileMode.Open, FileAccess.Read);
BufferedStream bstream = new BufferedStream(fsream);
fsream.Close();
StreamReader sr = new StreamReader("C:/Documents and Settings/Arian/Desktop/Perl (PERLC-09)/bookExamples/unitThree/menuLunch.txt");
while (!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
selection = Console.ReadLine();
问候
请您参考如下方法:
答案很简单。 File 类带有两个方便的方法,可帮助您从文件读取行或向文件写入行:
// Write
string path = "example.txt";
string[] myMenu = { "A", "B", "C" };
File.WriteAllLines(path, myMenu);
// Read
string[] readMenu = File.ReadAllLines(path);
