我想要读取和写入文件.这不起作用.
static void Main(string[] args) { StreamReader sr = new StreamReader(@"C:\words.txt"); StreamWriter sw = new StreamWriter(@"C:\words.txt"); }
我如何在C#中读取和写入文件?
您需要一个单独的流,为读取和写入打开.
FileStream fileStream = new FileStream( @"c:\words.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
不要忘记简单的路线:
static void Main(string[] args) { var text = File.ReadAllText(@"C:\words.txt"); File.WriteAllText(@"C:\words.txt", text + "DERP"); }
var fs = File.Open("file.name", FileMode.OpenOrCreate, FileAccess.ReadWrite); var sw = new StreamWriter(fs); var sr = new StreamReader(fs); ... fs.Close(); //or sw.Close();
关键是用FileAccess.ReadWrite标志打开文件.然后,您可以使用初始FileStream创建所需的任何Stream/String/Binary Reader/Writers.