【发布时间】:2018-01-28 18:23:13
【问题描述】:
我正在开发控制台应用程序,我正在尝试将列表保存到 txt 文件并稍后读取该数据。
在程序中用户输入类别名称,我不知道如何将其与 txt 文件中的列表一起保存。
包含名称的结构类别。
struct Category
{
public string name;
}
这是我目前的代码。
Category k;
Console.WriteLine("Enter name of category: ");
k.name = Console.ReadLine();
List<String> category = new List<string>();
TextWriter tw = new StreamWriter("../../dat.txt");
foreach (string k in category)
{
string[] en = s.Split(',');
category.Add(k.name); // Here I am not sure how to save name
}
tw.Close();
StreamReader sr = new StreamReader("../../dat.txt");
string data = sr.ReadLine();
while (data != null)
{
Console.WriteLine(data);
data = sr.ReadLine();
}
sr.Close();
它没有给我任何错误,但它没有将名称写入 txt 文件。
解决方案
string filePath = @"../../datoteka.txt";
List<String> kategorije = File.ReadAllLines(filePath).ToList();
foreach (string s in kategorije)
{
Console.WriteLine(s);
}
kategorije.Add(k.naziv);
File.WriteAllLines(filePath,kategorije);
【问题讨论】:
-
您实际上并没有使用
TextWriter写任何东西,即我希望看到tw.WriteLine(k.Name)或类似的东西。 -
在
category.Add(k.name)之后添加一行tw.WriteLine(k.name)... -
很多问题:你从不使用
tw来实际写任何东西;你尝试通过一个新的空列表foreach;您将k定义为Category结构,然后再次定义为foreach变量;s在s.Split中的任何内容都没有在您显示的代码中定义;List包含string值,而不是您的Category结构...
标签: c#