如何在 C# 中读取和写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/605685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:04:19  来源:igfitidea点击:

How to both read and write a file in C#

c#file-iofilestream

提问by

I want to both read from and write to a file. This doesn't work.

我想读取和写入文件。这不起作用。

static void Main(string[] args)
{
    StreamReader sr = new StreamReader(@"C:\words.txt");
    StreamWriter sw = new StreamWriter(@"C:\words.txt");
}

How can I both read from and write to a file in C#?

如何在 C# 中读取和写入文件?

回答by MikeW

You need a single stream, opened for both reading and writing.

您需要一个单一的流,为读取和写入而打开。

FileStream fileStream = new FileStream(
      @"c:\words.txt", FileMode.OpenOrCreate, 
      FileAccess.ReadWrite, FileShare.None);

回答by ScottS

var fs = File.Open("file.name", FileMode.OpenOrCreate, FileAccess.ReadWrite);
var sw = new StreamWriter(fs);
var sr = new StreamReader(fs);

...

fs.Close();
//or sw.Close();

The key thing is to open the file with the FileAccess.ReadWrite flag. You can then create whatever Stream/String/Binary Reader/Writers you need using the initial FileStream.

关键是用 FileAccess.ReadWrite 标志打开文件。然后,您可以使用初始 FileStream 创建您需要的任何 Stream/String/Binary Reader/Writers。

回答by ScottS

Don't forget the easy route:

不要忘记简单的路线:

    static void Main(string[] args)
    {
        var text = File.ReadAllText(@"C:\words.txt");
        File.WriteAllText(@"C:\words.txt", text + "DERP");
    }

回答by mbarthelemy

This thread seems to answer your question : simultaneous-read-write-a-file

该线程似乎回答了您的问题:同时读取-写入-文件

Basically, what you need is to declare two FileStream, one for read operations, the other for write operations. Writer Filestream needs to open your file in 'Append' mode.

基本上,您需要声明两个 FileStream,一个用于读取操作,另一个用于写入操作。Writer Filestream 需要以“附加”模式打开您的文件。

回答by Ipsita Paul

you can try this:"Filename.txt" file will be created automatically in the bin->debug folder everytime you run this code or you can specify path of the file like: @"C:/...". you can check ?xistance of "Hello" by going to the bin -->debug folder

你可以试试这个:“Filename.txt”文件将在每次运行此代码时自动在 bin->debug 文件夹中创建,或者你可以指定文件的路径,如:@"C:/..."。您可以通过转到 bin -->debug 文件夹来检查“Hello”的 ?xistance

P.S dont forget to add Console.Readline() after this code snippet else console will not appear.

PS 不要忘记在此代码片段之后添加 Console.Readline() 否则控制台将不会出现。

TextWriter tw = new StreamWriter("filename.txt");
        String text = "Hello";
        tw.WriteLine(text);
        tw.Close();

        TextReader tr = new StreamReader("filename.txt");
        Console.WriteLine(tr.ReadLine());
        tr.Close();

回答by Anonimys

Made an improvement code by @Ipsita - for use asynchronous read\writefile I/O

由@Ipsita 改进代码 - 用于异步读写文件 I/O

readonly string logPath = @"FilePath";
...
public async Task WriteToLogAsync(string dataToWrite)
{
    TextReader tr = new StreamReader(logPath);
    string data = await tr.ReadLineAsync();
    tr.Close();

    TextWriter tw = new StreamWriter(logPath);
    await tw.WriteLineAsync(data + dataToWrite);
    tw.Close();
}
...
await WriteToLogAsync("Write this to file");