visual-studio 将 Visual Studio 项目中的所有文件另存为 UTF-8
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/279673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save all files in Visual Studio project as UTF-8
提问by jesperlind
I wonder if it's possible to save all files in a Visual Studio 2008 project into a specific character encoding. I got a solution with mixed encodings and I want to make them all the same (UTF-8 with signature).
我想知道是否可以将 Visual Studio 2008 项目中的所有文件保存为特定的字符编码。我得到了一个混合编码的解决方案,我想让它们都一样(带有签名的 UTF-8)。
I know how to save single files, but how about all files in a project?
我知道如何保存单个文件,但如何保存项目中的所有文件?
采纳答案by Timwi
Since you're already in Visual Studio, why not just simply write the code?
既然您已经在 Visual Studio 中,为什么不简单地编写代码呢?
foreach (var f in new DirectoryInfo(@"...").GetFiles("*.cs", SearchOption.AllDirectories)) {
string s = File.ReadAllText(f.FullName);
File.WriteAllText (f.FullName, s, Encoding.UTF8);
}
Only three lines of code! I'm sure you can write this in less than a minute :-)
只有三行代码!我相信你可以在一分钟内写下这个:-)
回答by Broam
This may be of some help.
这可能会有所帮助。
link removed due to original reference being defaced by spam site.
由于原始参考被垃圾邮件站点破坏,链接被删除。
Short version: edit one file, select File -> Advanced Save Options. Instead of changing UTF-8 to Ascii, change it to UTF-8. Edit: Make sure you select the option that says no byte-order-marker (BOM)
简短版本:编辑一个文件,选择文件 -> 高级保存选项。不要将 UTF-8 更改为 Ascii,而是将其更改为 UTF-8。编辑:确保选择没有字节顺序标记(BOM)的选项
Set code page & hit ok. It seems to persist just past the current file.
设置代码页并点击确定。它似乎一直持续到当前文件之后。
回答by rasx
In case you need to do this in PowerShell, here is my little move:
如果您需要在 PowerShell 中执行此操作,这是我的小动作:
Function Write-Utf8([string] $path, [string] $filter='*.*')
{
[IO.SearchOption] $option = [IO.SearchOption]::AllDirectories;
[String[]] $files = [IO.Directory]::GetFiles((Get-Item $path).FullName, $filter, $option);
foreach($file in $files)
{
"Writing $file...";
[String]$s = [IO.File]::ReadAllText($file);
[IO.File]::WriteAllText($file, $s, [Text.Encoding]::UTF8);
}
}
回答by Martin v. L?wis
I would convert the files programmatically (outside VS), e.g. using a Python script:
我会以编程方式(在 VS 之外)转换文件,例如使用 Python 脚本:
import glob, codecs
for f in glob.glob("*.py"):
data = open("f", "rb").read()
if data.startswith(codecs.BOM_UTF8):
# Already UTF-8
continue
# else assume ANSI code page
data = data.decode("mbcs")
data = codecs.BOM_UTF8 + data.encode("utf-8")
open("f", "wb").write(data)
This assumes all files not in "UTF-8 with signature" are in the ANSI code page - this is the same what VS 2008 apparently also assumes. If you know that some files have yet different encodings, you would have to specify what these encodings are.
这假设所有不在“带签名的 UTF-8”中的文件都在 ANSI 代码页中 - 这与 VS 2008 显然也假设的相同。如果您知道某些文件具有不同的编码,则必须指定这些编码是什么。
回答by Bruce
Using C#:
1) Create a new ConsoleApplication, then install Mozilla Universal Charset Detector
2) Run code:
使用 C#:
1) 创建一个新的 ConsoleApplication,然后安装Mozilla Universal Charset Detector
2) 运行代码:
static void Main(string[] args)
{
const string targetEncoding = "utf-8";
foreach (var f in new DirectoryInfo(@"<your project's path>").GetFiles("*.cs", SearchOption.AllDirectories))
{
var fileEnc = GetEncoding(f.FullName);
if (fileEnc != null && !string.Equals(fileEnc, targetEncoding, StringComparison.OrdinalIgnoreCase))
{
var str = File.ReadAllText(f.FullName, Encoding.GetEncoding(fileEnc));
File.WriteAllText(f.FullName, str, Encoding.GetEncoding(targetEncoding));
}
}
Console.WriteLine("Done.");
Console.ReadKey();
}
private static string GetEncoding(string filename)
{
using (var fs = File.OpenRead(filename))
{
var cdet = new Ude.CharsetDetector();
cdet.Feed(fs);
cdet.DataEnd();
if (cdet.Charset != null)
Console.WriteLine("Charset: {0}, confidence: {1} : " + filename, cdet.Charset, cdet.Confidence);
else
Console.WriteLine("Detection failed: " + filename);
return cdet.Charset;
}
}
回答by podcast
I have created a function to change encoding files written in asp.net. I searched a lot. And I also used some ideas and codes from this page. Thank you.
我创建了一个函数来更改用 asp.net 编写的编码文件。我搜索了很多。我还使用了此页面中的一些想法和代码。谢谢你。
And here is the function.
这是功能。
Function ChangeFileEncoding(pPathFolder As String, pExtension As String, pDirOption As IO.SearchOption) As Integer
Dim Counter As Integer
Dim s As String
Dim reader As IO.StreamReader
Dim gEnc As Text.Encoding
Dim direc As IO.DirectoryInfo = New IO.DirectoryInfo(pPathFolder)
For Each fi As IO.FileInfo In direc.GetFiles(pExtension, pDirOption)
s = ""
reader = New IO.StreamReader(fi.FullName, Text.Encoding.Default, True)
s = reader.ReadToEnd
gEnc = reader.CurrentEncoding
reader.Close()
If (gEnc.EncodingName <> Text.Encoding.UTF8.EncodingName) Then
s = IO.File.ReadAllText(fi.FullName, gEnc)
IO.File.WriteAllText(fi.FullName, s, System.Text.Encoding.UTF8)
Counter += 1
Response.Write("<br>Saved #" & Counter & ": " & fi.FullName & " - <i>Encoding was: " & gEnc.EncodingName & "</i>")
End If
Next
Return Counter
End Function
It can placed in .aspx file and then called like:
它可以放在 .aspx 文件中,然后像这样调用:
ChangeFileEncoding("C:\temp\test", "*.ascx", IO.SearchOption.TopDirectoryOnly)
回答by Mase
if you are using TFS with VS : http://msdn.microsoft.com/en-us/library/1yft8zkw(v=vs.100).aspxExample :
如果您在 VS 中使用 TFS:http: //msdn.microsoft.com/en-us/library/1yft8zkw(v=vs.100) .aspx示例:
tf checkout -r -type:utf-8 src/*.aspx
回答by Ehsan
Thanks for your solutions, this code has worked for me :
感谢您的解决方案,此代码对我有用:
Dim s As String = ""
Dim direc As DirectoryInfo = New DirectoryInfo("Your Directory path")
For Each fi As FileInfo In direc.GetFiles("*.vb", SearchOption.AllDirectories)
s = File.ReadAllText(fi.FullName, System.Text.Encoding.Default)
File.WriteAllText(fi.FullName, s, System.Text.Encoding.Unicode)
Next
回答by Maxime Esprit
If you want to avoid this type of error :
如果你想避免这种类型的错误:
Use this following code :
使用以下代码:
foreach (var f in new DirectoryInfo(@"....").GetFiles("*.cs", SearchOption.AllDirectories))
{
string s = File.ReadAllText(f.FullName, Encoding.GetEncoding(1252));
File.WriteAllText(f.FullName, s, Encoding.UTF8);
}
Encoding number 1252 is the default Windows encoding used by Visual Studio to save your files.
编码编号 1252 是 Visual Studio 用于保存文件的默认 Windows 编码。
回答by Yitzhak Weinberg
the item is removed from the menu in Visual Studio 2017 You can still access the functionality through File-> Save As -> then clicking the down arrow on the Save button and clicking "Save With Encoding...".
该项目已从 Visual Studio 2017 的菜单中删除您仍然可以通过文件-> 另存为-> 然后单击保存按钮上的向下箭头并单击“使用编码保存...”来访问该功能。
You can also add it back to the File menu through Tools->Customize->Commands if you want to.
如果需要,您还可以通过工具->自定义->命令将其添加回文件菜单。


