简体   繁体   English

从txt文件读取和写入

[英]Reading and Writing from a txt file

I'm trying to read and write from a txt file using C#. 我正在尝试使用C#从txt文件读取和写入。 At the moment, I'm writing a program that reads the names in a list, shows them to the user, asks for another name, and then adds that one to the list. 目前,我正在编写一个程序,该程序读取列表中的名称,向用户显示这些名称,请求另一个名称,然后将该名称添加到列表中。 The reading is fine, but there's some problems with the writing. 阅读很好,但写作存在一些问题。

The code compiles fine using CSC, and it executes fine, but after I type the name to add and hit enter, I get a window popping up saying 代码使用CSC编译得很好,并且执行正常,但在我输入要添加的名称并按Enter后,我会弹出一个窗口说

FileIO.exe has encountered a problem and needs to close. FileIO.exe遇到问题,需要关闭。

Any idea what the problem is? 知道问题是什么吗?

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

You are getting the exception because you are not closing your reader , Just place reader.Close(); 你得到了例外,因为你没有关闭你的reader ,只需放置reader.Close(); after reading your file to Array. 将文件读入Array后。

Even better is to use using statement, since StreamReader uses IDisposable interface, this would ensure closing of the stream as well as its disposal. 更好的是使用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();
    }
}

Just a side note : 只是旁注

you are use File.ReadAllLines just to get Length ???, you can fillup your array like: 你使用File.ReadAllLines只是为了得到Length ???,你可以填充你的数组,如:

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

instead of going through StreamReader . 而不是通过StreamReader

How about we simplify this a bit: 我们如何简化这一点:

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):

Now you're not dealing with the IO at all because you're leaving it to the framework by leveraging those static methods wholly. 现在你根本没有处理IO,因为你通过完全利用这些静态方法将它留给了框架。

It's good to ensure that you learn of any exceptions at the top level of a console application: 确保您了解控制台应用程序顶层的任何异常是很好的:

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

This way, you'll know why the application had to close. 这样一来,你就知道为什么应用程序不得不关闭。

Additionally, you need to have your StreamReader in a using block. 此外,您需要将StreamReader放在using块中。

If you want to read all lines from a file into an array, you can simply use: 如果要将文件中的所有行读入数组,只需使用:

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

And use that array. 并使用该数组。

Use the reader.ReadToEnd function like this and don't forget to close the reader when you finish.: 使用这样的reader.ReadToEnd函数,不要忘记在完成时关闭阅读器:

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

The reason you get that exception is because you don't close the reader after reading. 您获得该异常的原因是因为您在阅读后没有关闭阅读器。 So you can't write to it without first calling the Close(); 因此,如果没有先调用Close(),就无法写入; method. 方法。

You can also use the using statement instead of closing it like this: 您也可以使用using语句而不是像这样关闭它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM