gpt4 book ai didi

c# - 读取文本文件并将信息保存到数组 C#

转载 作者:太空宇宙 更新时间:2023-11-03 22:07:31 25 4
gpt4 key购买 nike

早上好

我想咨询一下如何使用 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);

关于c# - 读取文本文件并将信息保存到数组 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7865562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com