I'm have a StringBuilder that is writing content to a file. Towards the end of each file, I'm writing the copyright symb开发者_JAVA百科ol. Oddly, I have noticed that whenever the copyright symbol is written, it is preceeded by a "Â". My code that generates the content of the file looks like this:
using (StringWriter stringWriter = new StringWriter())
{
stringWriter = GetFileContent();
string targetPath = ConfigurationManager.AppSettings["TargetPath"];
using (StreamWriter streamWriter = new StreamWriter(targetPath, false))
{
StringBuilder sb = new StringBuilder(stringWriter.ToString());
// Attempted fix
string content = sb.ToString();
content = content.Replace("Â", "");
streamWriter.Write(content);
}
}
As you can tell, I tried to do a find-and-replace. In the process, I noticed that a "Â" was not in the content itself. This makes me believe there is something occurring in the streamWriter. However, I'm not sure what it could be.
Can someone please tell me why a "Â" would be popping up before the "©" symbol and how to fix it? I believe it has something to do with encoding, but I'm not sure
Thank you!
The problem is almost certainly either how you're viewing the file afterwards (it will be saved as UTF-8) or how you're reading the contents of the existing file in GetFileContent()
. If you could give us more information on both of these points, I'm sure we'll find the answer.
The actual code you've got - though slightly odd and long-winded due to your attempts to fix things up - is fine.
My guess is that you're viewing the file with a text editor which is assuming Windows-1252 or something similar. If you can tell it to use UTF-8, I suspect it'll be fine.
精彩评论