Reputation: 9043
Good morning
I would like to enquire as to how to read a list from a text file and to save the info into a list(array) with c#.
Its a little exercise where I wrote the info to a text file and now I want to read the info and save it into a different array.
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();
regards
Upvotes: 1
Views: 2224
Reputation: 17691
you could try like this... it will stores the file contents in array when the form loads
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();
}
Upvotes: 1
Reputation: 13019
The answer is pretty simple. File
class comes in with two handy methods that help you to read and write lines from/to a file:
// Write
string path = "example.txt";
string[] myMenu = { "A", "B", "C" };
File.WriteAllLines(path, myMenu);
// Read
string[] readMenu = File.ReadAllLines(path);
Upvotes: 3