Reputation: 1457
this simply writes the text in textbox to the same file each time...I don't understand why it works perfectly if I input new characters or change characters while deleting characters doesn't work...
private void ContentChanged(object sender, TextChangedEventArgs e)
{
Console.WriteLine("cur before:" + this.Box.SelectionStart);
FileStream f = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter writer = new StreamWriter(f);
model.Cursor = this.Box.SelectionStart;
writer.Write(this.Box.Text);
writer.Close();
Console.WriteLine("cur after:" + this.Box.SelectionStart);
Console.WriteLine("write:" + count++);
Console.WriteLine("after write:" + this.Box.Text);
Console.WriteLine("after write:" + model.Content);
}
Upvotes: 0
Views: 447
Reputation: 1457
I found out why.
The StreamWriter constructor I used couldn't set the attribute "append" to false, so each time I'm overriding the existing text, not starting from scratch.
Since I have to use FileStream for multi-thread reason, I guess I would have to find another way of writing the file.
Upvotes: 0
Reputation: 5843
In short: you need to re-write your code like in the following sample by using
keyword. As it prevents the leaks and is recommended way to deal with un-managed resources in .NET Framework.
using(StreamWriter writer = new StreamWriter(Response.OutputStream))
{
writer.WriteLine("col1,col2,col3");
writer.WriteLine("1,2,3");
writer.Close(); //not necessary I think... end of using block should close writer
}
Edit: In your code sample you are opening the FileStream
but do not close it, which causes the issues. Thus, preventing that with a convenient using statement is proffered way to go. Otherwise, you just need to close your filstream or any un-managed resources.
Upvotes: 0
Reputation: 1500065
You're not closing f
or flushing - it's entirely possible that the data is being buffered, which is why it never makes it to the file.
Two suggestions:
using
statements with disposable resources such as streams and writersFile.CreateText
to create a TextWriter
in one call - or better yet, use File.WriteAllText
to avoid having to worry about opening and closing at all.So something like this:
private void ContentChanged(object sender, TextChangedEventArgs e)
{
Console.WriteLine("cur before:" + this.Box.SelectionStart);
File.WriteAllText(path, this.Box.Text);
Console.WriteLine("cur after:" + this.Box.SelectionStart);
Console.WriteLine("write:" + count++);
Console.WriteLine("after write:" + this.Box.Text);
Console.WriteLine("after write:" + model.Content);
}
Upvotes: 4