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

如何解决C#程序读取含韩文文件名文件的非法字符异常?

问题描述

代码示例

using System;
using System.IO;

namespace letstest
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = Console.ReadLine();
            File.OpenRead(Console.ReadLine());
        }
    }
}

问题现象

同一目录下存在a.txt和아.txt两个文件。输入a.txt时程序运行正常,但输入아.txt时会抛出异常。

未检查fileName变量的值,输入内容为"아.txt"时,具体报错如下:

아.txt

Unhandled Exception: System.ArgumentException: Illegal characters in path.
   at System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(String fullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.File.OpenRead(String path)
   at letstest.Program.Main(String[] args) in C:\Users\nasoo\source\repos\letstest\letstest\Program.cs:line 10

希望实现可读取含韩文文件名文件的程序,该如何解决此问题?


解决方案

1. 修复控制台输入编码问题

韩文属于Unicode字符,默认控制台输入编码可能不支持Unicode,导致读取的韩文被解析为非法字符。需设置控制台输入编码为UTF-8:

Console.InputEncoding = System.Text.Encoding.UTF8;

2. 修正代码逻辑错误

原代码定义了fileName变量却未使用,反而两次调用Console.ReadLine(),导致第一次输入的文件名被丢弃。修正为使用第一次读取的文件名:

static void Main(string[] args)
{
    Console.InputEncoding = System.Text.Encoding.UTF8;
    string fileName = Console.ReadLine();
    
    // 可选:先判断文件是否存在,避免异常
    if (File.Exists(fileName))
    {
        using (var stream = File.OpenRead(fileName))
        {
            // 此处添加文件读取逻辑
        }
    }
    else
    {
        Console.WriteLine("指定文件不存在");
    }
}

3. 启用长路径支持(可选)

若文件名包含特殊字符且路径较长,可通过配置启用长路径支持:
在项目的app.config或web.config中添加以下内容:

<configuration>
  <runtime>
    <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false" />
  </runtime>
</configuration>

核心原因说明

韩文本身并非非法路径字符,问题根源是控制台输入编码不匹配,导致读取的文件名被错误编码,进而被识别为非法字符。设置Console.InputEncoding为UTF-8后,即可正确读取Unicode字符文件名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:20:49