You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio打开C#项目默认编码错误,多种方法无效求助

C#项目在Visual Studio中默认编码异常的批量解决问题
  • 使用MS Visual Studio 2022打开C#项目时,文件默认编码异常,显示乱码。
  • 已尝试以下操作均无效:
    • 将系统「非Unicode程序语言」设置为「English (United States)」并取消Beta选项
    • 更换为VS 2019、重新从仓库拉取新项目
  • 发现单个文件可通过VS Code以GB2312编码打开后另存为UTF-8解决,但项目包含数千个此类文件,手动操作不可行。
  • 编写的Python批量转换脚本未生效,脚本代码如下:
import os

def convert_encoding(source_folder, target_encoding='utf-8'):
    # define files that I want to change encoding
    extensions = {'.cs', '.json'}

    for root, dirs, files in os.walk(source_folder):
        for file in files:
            # get extensions
            _, ext = os.path.splitext(file)
            # check 
            if ext.lower() in extensions:
                file_path = os.path.join(root, file)
                try:
                    # open with encoding gb2312
                    with open(file_path, 'rb') as f:
                        contents = f.read().decode('gb2312')
                    
                    # save as utf-8
                    with open(file_path, 'w', encoding=target_encoding) as f:
                        f.write(contents)
                    print(f"Converted {file_path} to {target_encoding}")
                except Exception as e:
                    print(f"Error converting {file_path}: {e}")

# set directory
source_folder = 'E:\my\project\file\dir'  
convert_encoding(source_folder)
  • 针对他人建议的尝试结果:
    • 按@Dai的建议,通过「文件>打开>文件>点击打开按钮旁箭头>选择编码打开」操作,未找到UTF-8编码选项,且仅支持逐个修改文件
    • 按@MarkRansom的建议,以UTF-8 SIG编码打开文件,仍存在编码错误

求有效解决方案,谢谢!

内容的提问来源于stack exchange,提问作者Bill Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 08:34:57