Cannot write to file after reading

后端 未结 5 884
悲哀的现实
悲哀的现实 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: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();
    }
    

提交回复
热议问题