我正在使用控制台应用程序,我正在尝试将列表保存到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文件。
SOLUTIN
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);
答案 0 :(得分:2)
您可以使用System.IO.File
类的静态方法。它们的优点是它们可以自动打开和关闭文件,从而将编写和读取文件的任务减少到单个语句
File.WriteAllLines(yourFilePath, category);
您可以使用
将这些行重新读回列表中 category = new List(ReadLines(yourFilePath));
ReadLines
返回IEnumerable<string>
,该列表在列表的构造函数中被接受为数据源。
或带
的数组string[] array = ReadAllLines(yourFilePath);
您的解决方案不会向输出流写入任何内容。您正在初始化TextWriter
但未使用它。你会像
tw.WriteLine(someString);
您的代码存在一些问题:您正在声明类别变量k
,但您从未为其分配类别。您的列表不属于类别类别。
更好的解决方案可以像这样工作
var categories = new List<Category>(); // Create a categories list.
while (true) { // Loop as long as the user enters some category name.
Console.WriteLine("Enter name of category: ");
string s = Console.ReadLine(); // Read user entry.
if (String.IsNullOrWhiteSpace(s)) {
// No more entries - exit loop
break;
}
// Create a new category and assign it the entered name.
var category = new Category { name = s };
//TODO: Prompt the user for more properties of the category and assign them to the
// category.
// Add the category to the list.
categories.Add(category);
}
File.WriteAllLines(yourFilePath, categories.Select(c => c.name));
Category
类型应为class。请参阅:When should I use a struct instead of a class?
答案 1 :(得分:0)
您没有使用WtiteLine来撰写内容。
之后在解决方案中添加以下代码category.Add(k.name);
tw.WriteLine(someString);
查找下面的读写示例代码。
class WriteTextFile
{
static void Main()
{
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);
string text = "A class is the most powerful data type in C#. Like a structure, " +
"a class defines the data and behavior of the data type. ";
System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
{
foreach (string line in lines)
{
if (!line.Contains("Second"))
{
file.WriteLine(line);
}
}
}
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
{
file.WriteLine("Fourth line");
}
}
}