[英]How to write and read list to text file that contains user input using c#
我正在使用控制台应用程序,正在尝试将列表保存到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);
您可以使用System.IO.File
类的静态方法。 它们的优点是它们自动打开和关闭文件,从而减少了将文件写入和读取到单个语句的任务
File.WriteAllLines(yourFilePath, category);
您可以将这些行读回到列表中
category = new List(ReadLines(yourFilePath));
ReadLines
返回IEnumerable<string>
,该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。 请参阅: 什么时候应该使用结构而不是类?
您没有使用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");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.