2011-10-23 33 views
1

早上好阅读文本文件和保存信息到一个数组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(); 

问候

+0

开始使用'using'关键字:'using(var fs = new FileStream(...)){...}',读一些关于一次性模式的内容。 –

回答

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(); 


} 
+0

谢谢...当然... arrayList! – Arianule

3

答案很简单。 File类来自于两个方便的方法,可帮助您读写线从/到一个文件:

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

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