简体   繁体   中英

How can I serialise a text file to elements in an array C#

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
    SaveFileDialog save = new SaveFileDialog();
    save.FileName = txtRecipeName.Text + ".MyRecipe";
    save.Filter = "Recipe File | *.MyRecipe";
    if (save.ShowDialog() == DialogResult.OK)
    {
        StreamWriter writer = new StreamWriter(save.OpenFile());

        for (int i = 0; i < ingredients.Count; i++)
        {
            writer.Write(ingredients[i] + ",");
            writer.Write(amount[i] + ",");
            writer.Write(units[i] + "\n");
        }

        writer.Dispose();
        writer.Close();
    }

}

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog open = new OpenFileDialog();
    open.ShowDialog();
    open.Filter = "Recipe Files|*.MyRecipe|All Files|*.*";
    open.FilterIndex = 1;

    StreamReader reader = new StreamReader(open.FileName);
}

My question is how can I make it so that the stream reader goes through the text file so that the first word after a new line is saved into the ingredients list and then the second words is saved into the amounts list and the third word is saved into the units lists.

Here is the output on the text file:

egg,5,Ounce
milk,54,Pint

You could use the split function of string:

IList<string> lstIngredients = new List<string>();
IList<string> lstAmount = new List<string>();
IList<string> lstUnits = new List<string>();

while(!reader.EndOfStream)
{
    string line = reader.ReadLine();
    var parts = line.Split(',');

    lstIngredients.Add(parts[0]);
    lstAmount.Add(parts[1]);
    lstUnits.Add(parts[2]);
}

ingredients = lstIngredients.ToArray();
amount = lstAmount.ToArray();
units = lstUnits.ToArray();

Using File.ReadAllLines and ForEach you can do it in one statement like:

var lstIngredients = new List<string>();
var lstAmount = new List<string>();
var lstUnits = new List<string>();

File.ReadAllLines("filePath")
    .ToList()
    .ForEach( (line) => { 
                          var words = line.Split(',');
                          lstIngredients.Add(words[0]);
                          lstAmount.Add(words[1]);
                          lstUnits.Add(words[2]);
                        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM