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

如何使用C#实现ASCII艺术输出并解决EndOfStreamException异常

C# ASCII艺术字输出问题修复

问题根因说明

  • EndOfStreamException异常原因:BinaryReader.ReadByte() 方法到达流末尾时不会返回-1,而是直接抛出System.IO.EndOfStreamException异常,你原有代码的循环判断逻辑是适配Stream.ReadByte()的,不适用于BinaryReader。
  • 输出结构错误原因:计数器count的初始值和递增逻辑错误,导致换行时机不符合每行11个字符的要求。

修正代码

方案1:保留BinaryReader写法

public void ESAOut(string Path)
{
    // using语法自动释放资源,避免手动关闭遗漏
    using BinaryReader reader = new BinaryReader(File.Open(Path, FileMode.Open));
    int count = 0;
    // 先判断流是否还有未读字节再执行读取
    while (reader.BaseStream.Position < reader.BaseStream.Length)
    {
        byte b = reader.ReadByte();
        Console.Write((char)b);
        count++;
        // 每满11个字符就换行
        if (count % 11 == 0)
        {
            Console.WriteLine();
        }
    }
}

方案2:简化读取逻辑(更稳定)

直接一次性读取全部字节再按规则输出,避免流读取的边界问题:

public void ESAOut(string Path)
{
    byte[] allBytes = File.ReadAllBytes(Path);
    for(int i = 0; i < allBytes.Length; i++)
    {
        Console.Write((char)allBytes[i]);
        if((i + 1) % 11 == 0)
        {
            Console.WriteLine();
        }
    }
}

额外优化建议

ESAIn方法也建议用using包裹FileStream,代替手动调用Close(),避免异常场景下资源泄漏。你提供的字节数组总长度恰好为7*11=77,修正代码运行后会正确输出7行ASCII艺术字,显示C#效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:36:07