【问题标题】:How to write and read list to text file that contains user input using c#如何使用 c# 将列表写入和读取包含用户输入的文本文件
【发布时间】: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) 或类似的东西。
  • Saving lists to txt file的可能重复
  • category.Add(k.name)之后添加一行tw.WriteLine(k.name) ...
  • 很多问题:你从不使用tw 来实际写任何东西;你尝试通过一个新的空列表foreach;您将k 定义为Category 结构,然后再次定义为foreach 变量; ss.Split 中的任何内容都没有在您显示的代码中定义; List 包含 string 值,而不是您的 Category 结构...

标签: c#


【解决方案1】:

您可以使用System.IO.File 类的静态方法。它们的优点是可以自动打开和关闭文件,从而将写入和读取文件的任务减少到单个语句

File.WriteAllLines(yourFilePath, category);

您可以将这些行读回列表中

 category = new List(ReadLines(yourFilePath));

ReadLines 返回一个IEnumerable&lt;string&gt;,该IEnumerable&lt;string&gt; 在列表的构造函数中被接受为数据源。

或放入数组中

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 类型应该是类。见:When should I use a struct instead of a class?

【讨论】:

  • 感谢您的回答。我设法根据它修复了我的代码。如果您检查我的问题,我已将其作为解决方案。 :) @Olivier Jacot-Descombes
【解决方案2】:

您没有使用 WtiteLine 来编写内容。在

之后在您的解决方案中添加以下代码
category.Add(k.name);
tw.WriteLine(someString);

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file

在下面找到用于读写的示例代码。

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");
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-26
    • 2021-10-29
    • 1970-01-01
    • 2017-06-18
    • 2012-09-15
    • 2021-05-25
    • 2021-03-23
    • 1970-01-01
    相关资源
    最近更新 更多