Cannot write to file after reading

后端 未结 5 874
悲哀的现实
悲哀的现实 2020-12-04 02:33

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

class Class1
{
    private static void Main()
    {
        FileStream fs = new F         


        
相关标签:
5条回答
  • 2020-12-04 03:00

    Do not close the StreamReader. Just comment the line below and it will work.

     r.Close();
    
    0 讨论(0)
  • 2020-12-04 03:09

    from msdn

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

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

    0 讨论(0)
  • 2020-12-04 03:10

    You'll have to re-open the file since the read closes it:

    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();
    
    0 讨论(0)
  • 2020-12-04 03:12
    r.Close(); 
    

    There's your problem after you read. The close() methods close the underlying stream.

    0 讨论(0)
  • 2020-12-04 03:24

    Dont close the first StreamWriter, it will close the underlying stream. And use using statements as Oscar suggests.

    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();
    }
    
    0 讨论(0)
提交回复
热议问题