读取后无法写入文件 [英] Cannot write to file after reading

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

问题描述

在以下代码中,我收到错误stream 不可写":

In the following code I get the error "stream was not writable":

class Class1
{
    private static void Main()
    {
        FileStream fs = new FileStream("C:\fFile.txt", 
                              FileMode.OpenOrCreate, 
                              FileAccess.ReadWrite, 
                              FileShare.ReadWrite);

        StreamReader r = new StreamReader(fs);
        string t = r.ReadLine();
        r.Close();
        Console.WriteLine(t);

        StreamWriter w = new StreamWriter(fs);
        w.WriteLine("string");
        w.Flush();
        w.Close();
        fs.Close();

    }
}    

错误发生在这一行 StreamWriter w = new StreamWriter(fs);

这是为什么?

推荐答案

来自 msdn

关闭 StreamReader 对象和底层流,并释放与读取器关联的所有系统资源.

因此您尝试写入的流无效,您需要重新打开流并重新打开文件.

So the stream you try to write to is invalid you need to reopen the stream and reopen the file.

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

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