我有一个愚蠢的问题。我正在从磁盘读取一些 .cs 文件。 使用我制作的 .net 程序对它们进行大量正则表达式和其他操作。 然后将它们写回光盘。
生成的文件以某种方式得到了错误的编码。 c#源文件是什么编码?然后是第一个字节顺序,是否需要? 当我使用 File.WriteAllText() 时它会被写入吗?
更改文件的程序是一个简单的.net应用程序,代码也很简单
string text = System.IO.File.ReadAllText(fn);
string newText = Regex.Replace(text, regexStr, replaceStr);
System.IO.File.WriteAllText(fn, newText);
C# 文件有注释,字符串似乎不是标准代码页的一部分。
其中一个有问题的字符是“ä”
解决方案:
这似乎工作正常
string text = System.IO.File.ReadAllText(fn, Encoding.GetEncoding(1252));
string newText = Regex.Replace(text, regexStr, replaceStr);
System.IO.File.WriteAllText(fn, newText, Encoding.GetEncoding(1252));
最佳答案
System.IO.File.ReadAllText(fn)
尝试猜测输入文件的编码。这可能会出错。
Visual Studio 2008 默认以 UTF-8 格式创建文件。同样,您应该尽可能使用 UTF-8,方法是在将文件写入磁盘时指定 Encoding.UTF8Encoding
。
关于c# - 将 C# 源代码写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/681446/