从 txt 文件读取和写入

本文关键字:读取 txt 文件 | 更新日期: 2023-09-27 18:34:24

我正在尝试使用 C# 从 txt 文件读取和写入。目前,我正在编写一个程序,该程序读取列表中的名称,向用户显示它们,请求另一个名称,然后将该名称添加到列表中。阅读很好,但写作有一些问题。

代码使用 CSC 编译良好,执行良好,但是在我键入要添加的名称并按回车键后,我弹出一个窗口说

文件IO.exe遇到问题,需要关闭。

知道问题是什么吗?

using System;
using System.IO;
public class Hello1
{
    public static void Main()
    {   
        int lines = File.ReadAllLines("Name.txt").Length;
        string[] stringArray = new string[lines + 1];
        StreamReader reader = new StreamReader("Name.txt");
        for(int i = 1;i <=lines;i++){
            stringArray[i-1] = reader.ReadLine();
        }
        for (int i = 1;i <=stringArray.Length;i++){
            Console.WriteLine(stringArray[i-1]);
        }
        Console.WriteLine("Please enter a name to add to the list.");
        stringArray[lines] = Console.ReadLine();
        using (System.IO.StreamWriter writer = new System.IO.StreamWriter("Name.txt", true)){
            writer.WriteLine(stringArray[lines]);
        }
    }
}

从 txt 文件读取和写入

你得到异常是因为你没有关闭你的reader,只需在将文件读取到数组后放置reader.Close();即可。

更好的是使用 using 语句,因为StreamReader使用IDisposable接口,这将确保流的关闭及其处置。

string[] stringArray = new string[lines + 1];
using (StreamReader reader = new StreamReader("Name.txt"))
{
    for (int i = 1; i <= lines; i++)
    {
        stringArray[i - 1] = reader.ReadLine();
    }
}

只是一个旁注

你使用File.ReadAllLines只是为了获得Length ???,你可以像这样填充你的数组:

string[] stringArray = File.ReadAllLines("Name.txt");

而不是经历StreamReader.

我们简化一下怎么样:

foreach (var line in File.ReadLines("Name.txt"))
{
    Console.WriteLine(line);
}
Console.WriteLine("Please enter a name to add to the list.");
var name = Console.ReadLine();
File.AppendLine("Name.txt", name):

现在你根本不处理 IO,因为你通过完全利用这些静态方法将其留给框架。

最好确保在控制台应用程序的顶层了解任何异常:

public class Hello1
{
    public static void Main()
    {
        try
        {
            // whatever
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception!);
            Console.WriteLine(ex.ToString());
        }
        finally
        {
            Console.Write("Press ENTER to exit: ");
            Console.ReadLine();
        }
    }
}

这样,您就会知道为什么必须关闭应用程序。

此外,您需要将StreamReader放在using块中。

如果要将文件中的所有行读取到数组中,只需使用:

string[] lines = File.ReadAllLines("Name.txt");

并使用该数组。

使用阅读器。ReadToEnd 功能如下,完成后不要忘记关闭阅读器。

StreamReader reader = new StreamReader("Name.txt");
string content = reader.ReadToEnd();
reader.Close();

您出现该异常的原因是您在阅读后没有关闭阅读器。因此,如果不先调用 Close(),就无法写入它;方法。

您也可以使用 using 语句,而不是像这样关闭它:

using (StreamReader reader = new StreamReader("Name.txt")){
    string content = reader.ReadToEnd();
};