'Convert all *.cs files to unicode in VisualStudio
My team does not pay attention to file encoding (and that is correct, because humans should not be bothered by file encodings). However some files are saved in utf8, and some in regional encoding (cp1250).
I need to do two things:
- Force utf8 on all files that will be created in future
- Convert all existing files with given extension (or at least *.cs) to utf-8
How can I achieve these goals using Visual-Studio, Resharper plugins, or Powershell?
I tried to do #2 with PowerShell, however it is mess (sometimes it removes/adds last line). Probably there is some free software that I can use to do it, point #1 is more important for me.
Solution 1:[1]
Re. #1: There is the option
Environment | Documents | Save documents as Unicode when data cannot be saved in codepage
but that isn't always. It appears there is no way to force this (and no likely extensions). Ever considered writing an extension :-) ?
Re. #2: it should be doable with PSH (but no final end of line might mess up the simplest approaches). However see https://stackoverflow.com/a/850751/67392
Edit: This seems to be a common request (see User Voice). One of the comments on that User Voice requests that in VS2017 you can use .editorconfig to set the default encoding of files.
Solution 2:[2]
Powershell 5.1 script, run in source root
Get-ChildItem -Include *.cs -Recurse | ForEach-Object {
$file = $_.FullName
$mustReWrite = $false
# Try to read as UTF-8 first and throw an exception if
# invalid-as-UTF-8 bytes are encountered.
try
{
[IO.File]::ReadAllText($file,[Text.Utf8Encoding]::new($false, $true))
}
catch [System.Text.DecoderFallbackException]
{
# Fall back to Windows-1250
$content = [IO.File]::ReadAllText($file,[Text.Encoding]::GetEncoding(1250))
$mustReWrite = $true
}
# Rewrite as UTF-8 without BOM (the .NET frameworks' default)
if ($mustReWrite)
{
Write "Converting from 1250 to UTF-8"
[IO.File]::WriteAllText($file, $content)
}
else
{
Write "Already UTF-8-encoded"
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | Marek Bednář |
