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);
}
我的问题是如何制作它以便流阅读器浏览文本文件,以便将新行后的第一个单词保存到成分列表中,然后将第二个单词保存到金额列表和第三个单词中单词保存在单位列表中。
以下是文本文件的输出:
egg,5,Ounce
milk,54,Pint
答案 0 :(得分:1)
您可以使用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();
答案 1 :(得分:1)
使用File.ReadAllLines
和ForEach
,您可以在以下语句中执行此操作:
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]);
});