读取textFile并将信息保存到数组中

本文关键字:数组 保存 信息 textFile 读取 | 更新日期: 2023-09-27 18:12:12

早上好

我想询问如何从文本文件中读取列表,并使用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();

读取textFile并将信息保存到数组中

答案很简单。File类提供了两个方便的方法,可以帮助您从/到文件读取和写入行:

// Write
string path = "example.txt";
string[] myMenu = { "A", "B", "C" };
File.WriteAllLines(path, myMenu);
// Read
string[] readMenu = File.ReadAllLines(path);

你可以试试这样…它将在表单加载

时将文件内容存储在数组中。
  private ArrayList statusArray = new ArrayList();
private void btnCompleted_Click(object sender, EventArgs e) {
    for (int i = 0; i < statusArray.Count; i++)
    {
        if (statusArray[i].Equals("Complete"))
            lstReports.Items.Add(statusArray[i-2]);
    }
}
private void Reports_Load(object sender, EventArgs e)
{
    // declare variables
    string inValue;
    string data;
    inFile = new StreamReader("percent.txt");
    // Read each line from the text file
    while ((inValue = inFile.ReadLine()) != null)
    {
        data = Convert.ToString(inValue);
        statusArray.Add(inValue);
    }
    // Close the text file
    inFile.Close();

}