I have a file which contains several text entries, say
one
two
three
Now, I need to delete one of the entries, say “two”. I’m using StreamReader and StreamWriter classes. In order to delete, first, I read the contents of the file into a string using StreamReader class, replace the “two\r\n” in the read string with “” and then, I write this string to the file using the StreamWriter class. But, since the length of the newly written string i.e. “one\r\nthree\r\n” is less than the original string i.e. “one\r\ntwo\r\nthree\r\n”, the first few characters get overwritten and the characters near the end still stay there giving rise to “one\r\nthree\r\nree\r\n”. Seems like a simple problem but, it has me stuck. Any ideas?
The user variable contains the entry to be deleted.
string all = "";
using (IsolatedStorageFileStream isoStream = store.OpenFile("user_list", FileMode.Open))
{
using (StreamReader sr = new StreamReader(isoStream))
{
all = sr.ReadToEnd();
all = all.Replace(user + "\r\n", "");
}
}
using (IsolatedStorageFileStream isoStream = store.OpenFile("user_list", FileMode.Open))
{
using (StreamWriter sw = new StreamWriter(isoStream))
{
sw.Write(all);
sw.Flush();
}
}
You can fix the problem by changing
FileMode.OpentoFileMode.Createwhen you’re opening the output file. That is:That will overwrite the previous file.