如何读取和写入在C#中的文件 [英] How to both read and write a file in C#

查看:153
本文介绍了如何读取和写入在C#中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要同时读取和写入文件。这是行不通的。

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

我怎样才能既读取和写入文件在C#?

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

推荐答案

您需要一个单一的数据流,打开阅读和写作。

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

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

这篇关于如何读取和写入在C#中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆