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

时间:2011-10-23 10:22:20

标签: c#

早上好

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

问候

2 个答案:

答案 0 :(得分:3)

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

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

// Read
string[] readMenu = File.ReadAllLines(path);

答案 1 :(得分:1)

你可以尝试这样......当表单加载

时,它会将文件内容存储在数组中
  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();


}