C# - 文件编码问题
我有一个 StringBuilder 正在将内容写入文件。在每个文件的末尾,我都会写下版权符号。奇怪的是,我注意到每当写入版权符号时,它前面都会有一个“”。我生成文件内容的代码如下所示:
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);
}
}
如您所知,我尝试进行查找和替换。在此过程中,我注意到内容本身并没有“”。这让我相信 StreamWriter 中发生了一些事情。但是,我不确定它可能是什么。
有人可以告诉我为什么在“©”符号之前会弹出一个“”以及如何修复它吗?我相信这与编码有关,但我不确定
谢谢!
I'm have a StringBuilder that is writing content to a file. Towards the end of each file, I'm writing the copyright symbol. 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
几乎可以肯定,问题出在您之后如何查看文件(它将保存为 UTF-8),或者您如何在
GetFileContent()
中读取现有文件的内容。如果您能为我们提供有关这两点的更多信息,我相信我们会找到答案。你得到的实际代码 - 尽管由于你尝试修复问题而有点奇怪和冗长 - 很好。
我的猜测是您正在使用文本编辑器查看该文件,该文本编辑器假定为 Windows-1252 或类似的版本。如果你能告诉它使用 UTF-8,我怀疑它会没问题。
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.