2011-07-15 126 views
2

在下面的代碼後的文件我得到的錯誤「流是不可寫」:無法寫入讀取

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

這是爲什麼?

回答

3

從MSDN

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

所以你嘗試寫入數據流是無效的,你需要重新打開該流並重新打開該文件。

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(); 
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(); 
} 
2
r.Close(); 

你看了之後有你的問題。 close()方法關閉底層流。

0

請勿關閉StreamReader。只需評論下面的行,它會起作用。

r.Close();