Problem with C# StreamWriter
The following code reads a file (one at a time from an array) into a string, replaces a matched pattern inside the string, then appends it to the file.
I want it to overwrite, instead of append. What am I doing wrong here?
using (FileStream fs = new FileStream(fileList[i], FileMode.Open))
using (StreamReader fileIn = new StreamReader(fs, true))
{
String file = fileIn.ReadToEnd().ToLower();
MessageBox.Show(file);
if (file.Contains(oPath))
{
updated++;
file = file.Replace(oPath, nPath);
using (StreamWriter replaceString = new StreamWriter(fs, Encoding.Unicode))
{
开发者_如何学编程 replaceString.Write(file);
listBoxResults.Items.Add(fileList[i]);
}
}
}
You're writing to the file after reading from it - so the "cursor" in the FileStream
is at the end.
Rather than handling the stream yourself, it would be simpler to use:
String file = File.ReadAllText(fileList[i]).ToLower();
... perform replacements etc ...
File.WriteAllText(fileList[i], file);
The second parameter of "StreamWriter" is: "append". So you should try:
StreamWriter replaceString = new StreamWriter(fs, false, Encoding.Unicode)
精彩评论