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

C#如何从FileStream读取字节数组并按每行11字节输出7行

问题原因

你原有代码用StreamReader.ReadLine()读取的逻辑不适用的核心原因是:你写入文件的字节数组没有包含任何换行符,ReadLine()会一次性读取全部内容返回,自然无法实现每11字节输出一行的要求。

修改要点

  • 修复写入方法硬编码文件路径的问题,使用传入的Path参数
  • 所有IO操作改用using语句自动释放资源,无需手动调用Close(),避免文件句柄泄漏
  • 读取文件时直接按字节读取,每次处理11字节转成ASCII字符输出,刚好匹配7行的要求

完整修改后代码

using System;
using System.IO;
using System.Text;

namespace ESA_2
{
    class Program
    {
        public void ESA2In(string Path)
        {
            byte[] array = {32, 32, 67, 67, 32, 32, 32, 35, 32, 35, 32,
                            32, 67, 32, 32, 67, 32, 32, 35, 32, 35, 32,
                            67, 32, 32, 32, 32, 32, 35, 35, 35, 35, 35,
                            67, 32, 32, 32, 32, 32, 32, 35, 32, 35, 32,
                            67, 32, 32, 32, 32, 32, 35, 35, 35, 35, 35,
                            32, 67, 32, 32, 67, 32, 32, 35, 32, 35, 32,
                            32, 32, 67, 67, 32, 32, 32, 35, 32, 35, 32 };
            // 使用using自动释放FileStream
            using FileStream stream = File.Open(Path, FileMode.Create);
            stream.Write(array, 0, array.Length);
        }

        public void ESA2Out(string Path)
        {
            // 一次性读取全部字节(总长度77,刚好7*11)
            byte[] fileContent = File.ReadAllBytes(Path);
            // 循环7次,每次取11字节转字符串输出
            for (int i = 0; i < 7; i++)
            {
                string line = Encoding.ASCII.GetString(fileContent, i * 11, 11);
                Console.WriteLine(line);
            }
        }

        static void Main(string[] args)
        {
            string Path = @"C:\users\...\test.txt";
            Program test = new Program();
            test.ESA2In(Path);
            test.ESA2Out(Path);
        }
    }
}

输出效果

运行后控制台会输出7行内容,前半部分是C组成的空心爱心,后半部分是#组成的空心爱心,完全符合排版要求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:15:03