将Visual Studio项目中的所有文件保存为UTF-8

时间:2023-01-06 11:15:45

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?

我知道如何保存单个文件,但项目中的所有文件怎么样?

12 个解决方案

#1


61  

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 :-)

只有三行代码!我相信你可以在不到一分钟内写出来:-)

#2


37  

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.

设置代码页并点击确定。它似乎只是暂存在当前文件之后。

#3


11  

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);
    }
}

#4


7  

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显然也假设的相同。如果您知道某些文件具有不同的编码,则必须指定这些编码是什么。

#5


3  

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;
    }
}

#6


1  

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)

#7


1  

if you are using TFS with VS : http://msdn.microsoft.com/en-us/library/1yft8zkw(v=vs.100).aspx Example :

如果您在VS中使用TFS:http://msdn.microsoft.com/en-us/library/1yft8zkw(v = vs.100).aspx示例:

tf checkout -r -type:utf-8 src/*.aspx

#8


1  

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

#9


1  

If you want to avoid this type of error :

如果要避免此类错误:

将Visual Studio项目中的所有文件保存为UTF-8

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编码。

#10


0  

I'm only offering this suggestion in case there's no way to automatically do this in Visual Studio (I'm not even sure this would work):

我只是提供这个建议,以防无法在Visual Studio中自动执行此操作(我甚至不确定这会起作用):

  1. Create a class in your project named 足の不*なハッキング (or some other unicode text that will force Visual Studio to encode as UTF-8).
  2. 在项目中创建一个名为“足の不*なハッキング”的类(或其他一些强制Visual Studio编码为UTF-8的unicode文本)。

  3. Add "using MyProject.足の不*なハッキング;" to the top of each file. You should be able to do it on everything by doing a global replace of "using System.Text;" with "using System.Text;using MyProject.足の不*なハッキング;".
  4. 添加“使用MyProject。足の不*なハッキング;”到每个文件的顶部。您应该能够通过全局替换“using System.Text”来完成所有操作。用“使用System.Text;使用MyProject。足の不*なハッキング;”。

  5. Save everything. You may get a long string of "Do you want to save X.cs using UTF-8?" messages or something.
  6. 保存一切。你可能得到一长串“你想用UTF-8保存X.cs吗?”消息或其他东西。

#11


0  

Experienced encoding problems after converting solution from VS2008 to VS2015. After conversion all project files was encoded in ANSI, but they contained UTF8 content and was recongnized as ANSI files in VS2015. Tried many conversion tactics, but worked only this solution.

将解决方案从VS2008转换为VS2015后出现了经验丰富的编码问题。转换后,所有项目文件都以ANSI编码,但它们包含UTF8内容,并在VS2015中被识别为ANSI文件。试过很多转换策略,但只使用这个解决方案。

 Encoding encoding = Encoding.Default;
 String original = String.Empty;
 foreach (var f in new DirectoryInfo(path).GetFiles("*.cs", SearchOption.AllDirectories))
 {
    using (StreamReader sr = new StreamReader(f.FullName, Encoding.Default))
    {
       original = sr.ReadToEnd();
       encoding = sr.CurrentEncoding;
       sr.Close();
    }
    if (encoding == Encoding.UTF8)
       continue;
    byte[] encBytes = encoding.GetBytes(original);
    byte[] utf8Bytes = Encoding.Convert(encoding, Encoding.UTF8, encBytes);
    var utf8Text = Encoding.UTF8.GetString(utf8Bytes);

    File.WriteAllText(f.FullName, utf8Text, Encoding.UTF8);
 }

#12


0  

adapted the version above to make it work.

修改了上面的版本以使其工作。

// important! create a utf8 encoding that explicitly writes no BOM            
var utf8nobom = new UTF8Encoding(false); 
foreach (var f in new DirectoryInfo(dir).GetFiles("*.*", SearchOption.AllDirectories))
{
    string text = File.ReadAllText(f.FullName);
    File.WriteAllText(f.FullName, text, utf8nobom);
}

#1


61  

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 :-)

只有三行代码!我相信你可以在不到一分钟内写出来:-)

#2


37  

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.

设置代码页并点击确定。它似乎只是暂存在当前文件之后。

#3


11  

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);
    }
}

#4


7  

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显然也假设的相同。如果您知道某些文件具有不同的编码,则必须指定这些编码是什么。

#5


3  

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;
    }
}

#6


1  

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)

#7


1  

if you are using TFS with VS : http://msdn.microsoft.com/en-us/library/1yft8zkw(v=vs.100).aspx Example :

如果您在VS中使用TFS:http://msdn.microsoft.com/en-us/library/1yft8zkw(v = vs.100).aspx示例:

tf checkout -r -type:utf-8 src/*.aspx

#8


1  

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

#9


1  

If you want to avoid this type of error :

如果要避免此类错误:

将Visual Studio项目中的所有文件保存为UTF-8

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编码。

#10


0  

I'm only offering this suggestion in case there's no way to automatically do this in Visual Studio (I'm not even sure this would work):

我只是提供这个建议,以防无法在Visual Studio中自动执行此操作(我甚至不确定这会起作用):

  1. Create a class in your project named 足の不*なハッキング (or some other unicode text that will force Visual Studio to encode as UTF-8).
  2. 在项目中创建一个名为“足の不*なハッキング”的类(或其他一些强制Visual Studio编码为UTF-8的unicode文本)。

  3. Add "using MyProject.足の不*なハッキング;" to the top of each file. You should be able to do it on everything by doing a global replace of "using System.Text;" with "using System.Text;using MyProject.足の不*なハッキング;".
  4. 添加“使用MyProject。足の不*なハッキング;”到每个文件的顶部。您应该能够通过全局替换“using System.Text”来完成所有操作。用“使用System.Text;使用MyProject。足の不*なハッキング;”。

  5. Save everything. You may get a long string of "Do you want to save X.cs using UTF-8?" messages or something.
  6. 保存一切。你可能得到一长串“你想用UTF-8保存X.cs吗?”消息或其他东西。

#11


0  

Experienced encoding problems after converting solution from VS2008 to VS2015. After conversion all project files was encoded in ANSI, but they contained UTF8 content and was recongnized as ANSI files in VS2015. Tried many conversion tactics, but worked only this solution.

将解决方案从VS2008转换为VS2015后出现了经验丰富的编码问题。转换后,所有项目文件都以ANSI编码,但它们包含UTF8内容,并在VS2015中被识别为ANSI文件。试过很多转换策略,但只使用这个解决方案。

 Encoding encoding = Encoding.Default;
 String original = String.Empty;
 foreach (var f in new DirectoryInfo(path).GetFiles("*.cs", SearchOption.AllDirectories))
 {
    using (StreamReader sr = new StreamReader(f.FullName, Encoding.Default))
    {
       original = sr.ReadToEnd();
       encoding = sr.CurrentEncoding;
       sr.Close();
    }
    if (encoding == Encoding.UTF8)
       continue;
    byte[] encBytes = encoding.GetBytes(original);
    byte[] utf8Bytes = Encoding.Convert(encoding, Encoding.UTF8, encBytes);
    var utf8Text = Encoding.UTF8.GetString(utf8Bytes);

    File.WriteAllText(f.FullName, utf8Text, Encoding.UTF8);
 }

#12


0  

adapted the version above to make it work.

修改了上面的版本以使其工作。

// important! create a utf8 encoding that explicitly writes no BOM            
var utf8nobom = new UTF8Encoding(false); 
foreach (var f in new DirectoryInfo(dir).GetFiles("*.*", SearchOption.AllDirectories))
{
    string text = File.ReadAllText(f.FullName);
    File.WriteAllText(f.FullName, text, utf8nobom);
}