Visual Studio 프로젝트의 모든 파일을 UTF-8로 저장
Visual Studio 2008 프로젝트의 모든 파일을 특정 문자 인코딩으로 저장할 수 있는지 궁금합니다. 혼합 인코딩 솔루션이 있고 모두 동일하게 만들고 싶습니다 (서명이있는 UTF-8).
단일 파일을 저장하는 방법을 알고 있지만 프로젝트의 모든 파일은 어떻습니까?
이미 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);
}
단 3 줄의 코드! 나는 당신이 1 분 안에 이것을 쓸 수 있다고 확신합니다 :-)
도움이 될 수 있습니다.
스팸 사이트에 의해 원본 참조가 손상되어 링크가 제거되었습니다.
짧은 버전 : 하나의 파일을 편집하고 파일-> 고급 저장 옵션을 선택합니다. UTF-8을 Ascii로 변경하는 대신 UTF-8로 변경하십시오. 편집 : 바이트 순서 마커 (BOM) 없음이라는 옵션을 선택했는지 확인하십시오.
코드 페이지를 설정하고 확인을 누르십시오. 현재 파일을 지나서 지속되는 것 같습니다.
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);
}
}
예를 들어 Python 스크립트를 사용하여 프로그래밍 방식으로 (VS 외부) 파일을 변환합니다.
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)
이것은 "서명이있는 UTF-8"에없는 모든 파일이 ANSI 코드 페이지에 있다고 가정합니다. 이것은 VS 2008에서도 분명히 가정하는 것과 동일합니다. 일부 파일의 인코딩이 아직 다르다는 것을 알고 있다면 이러한 인코딩이 무엇인지 지정해야합니다.
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;
}
}
asp.net으로 작성된 인코딩 파일을 변경하는 기능을 만들었습니다. 나는 많이 검색했다. 그리고이 페이지의 아이디어와 코드도 사용했습니다. 감사합니다.
그리고 여기에 기능이 있습니다.
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
.aspx 파일에 배치 한 다음 다음과 같이 호출 할 수 있습니다.
ChangeFileEncoding("C:\temp\test", "*.ascx", IO.SearchOption.TopDirectoryOnly)
if you are using TFS with VS : http://msdn.microsoft.com/en-us/library/1yft8zkw(v=vs.100).aspx Example :
tf checkout -r -type:utf-8 src/*.aspx
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
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.
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):
- Create a class in your project named 足の不自由なハッキング (or some other unicode text that will force Visual Studio to encode as UTF-8).
- 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.足の不自由なハッキング;".
- Save everything. You may get a long string of "Do you want to save X.cs using UTF-8?" messages or something.
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.
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);
}
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);
}
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...".
You can also add it back to the File menu through Tools->Customize->Commands if you want to.
참고URL : https://stackoverflow.com/questions/279673/save-all-files-in-visual-studio-project-as-utf-8
'developer tip' 카테고리의 다른 글
클래스의 함수 앞에있는 "get"키워드는 무엇입니까? (0) | 2020.10.10 |
---|---|
명령 줄을 애니메이션하는 방법은 무엇입니까? (0) | 2020.10.10 |
ASP.NET 사용자 지정 404에서 404 찾을 수 없음 대신 200 OK 반환 (0) | 2020.10.10 |
Select Top 100 %를 사용하는 이유는 무엇입니까? (0) | 2020.10.10 |
django-celery로 단위 테스트? (0) | 2020.10.10 |