阅读后无法写入文件

时间:2011-07-15 18:05:13

标签: c# file-io

在以下代码中,我收到错误“ stream is 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);

发生错误

为什么会这样?

5 个答案:

答案 0 :(得分:3)

来自msdn

Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.

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

答案 1 :(得分:2)

r.Close(); 

阅读后出现问题。 close()方法关闭基础流。

答案 2 :(得分:1)

您必须重新打开该文件,因为阅读将其关闭:

FileStream fs = new FileStream("C:\\test.txt", 
                        FileMode.OpenOrCreate, 
                        FileAccess.ReadWrite, 
                        FileShare.ReadWrite);
using (StreamReader r = new StreamReader(fs))
{
    string t = r.ReadLine();
    r.Close();
    Console.WriteLine(t);
}

fs = new FileStream("C:\\test.txt", 
            FileMode.OpenOrCreate, 
            FileAccess.ReadWrite, 
            FileShare.ReadWrite);

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

答案 3 :(得分:0)

不要关闭第一个StreamWriter,它会关闭基础流。 并使用奥斯卡建议使用的陈述。

using (FileStream fs = new FileStream("C:\\temp\\fFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
    StreamReader r = new StreamReader(fs);
    string t = r.ReadLine();

    Console.WriteLine(t);

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

答案 4 :(得分:0)

不要关闭StreamReader。只需对下面的行进行评论即可。

 r.Close();