I want to both read from and write to a file. This doesn't work.
static void Main(string[] args)
{
StreamReader sr = new StreamReader(@"C:\words.txt");
StreamWriter sw = new StreamWriter(@"C:\words.txt");
}
How can I both read from and write to a file in C#?
You need a single stream, opened for both reading and writing.
FileStream fileStream = new FileStream(
@"c:\words.txt", FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None);
Don't forget the easy route:
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();
The key thing is to open the file with the FileAccess.ReadWrite flag. You can then create whatever Stream/String/Binary Reader/Writers you need using the initial FileStream.
This thread seems to answer your question : simultaneous-read-write-a-file
Basically, what you need is to declare two FileStream, one for read operations, the other for write operations. Writer Filestream needs to open your file in 'Append' mode.