c#stream

在C#中,Stream 是一个抽象基类,用于处理输入和输出的字节序列。它是所有输入/输出 (I/O) 操作的基础,包括文件操作、网络操作、内存操作等。Stream 类提供了一组方法和属性,使得可以对数据进行读取、写入和定位。下面是一些Stream类的基本使用方法:

  1. 创建一个FileStream并写入数据:
csharp 复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 创建文件流
        using (FileStream fs = new FileStream("data.txt", FileMode.Create))
        {
            // 将数据写入文件
            byte[] data = new byte[] { 65, 66, 67, 68, 69 };
            fs.Write(data, 0, data.Length);
        }
    }
}
  1. 读取FileStream中的数据:
csharp 复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 打开文件流
        using (FileStream fs = new FileStream("data.txt", FileMode.Open))
        {
            // 读取文件中的数据
            byte[] buffer = new byte[1024];
            int bytesRead = fs.Read(buffer, 0, buffer.Length);
            Console.WriteLine("Data read from file: " + Encoding.UTF8.GetString(buffer, 0, bytesRead));
        }
    }
}
  1. 使用MemoryStream进行内存操作:
csharp 复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 使用内存流写入数据
        using (MemoryStream ms = new MemoryStream())
        {
            byte[] data = new byte[] { 70, 71, 72, 73, 74 };
            ms.Write(data, 0, data.Length);

            // 读取内存流中的数据
            ms.Position = 0;
            byte[] buffer = new byte[1024];
            int bytesRead = ms.Read(buffer, 0, buffer.Length);
            Console.WriteLine("Data read from memory stream: " + Encoding.UTF8.GetString(buffer, 0, bytesRead));
        }
    }
}

上述示例演示了如何使用 FileStreamMemoryStream 进行基本的读取和写入操作。Stream 类还有许多其他派生类,如 NetworkStream, CryptoStream 等,可根据不同的需求选择合适的流类型来进行I/O操作。

相关推荐
wenroudelang88881 小时前
Visual Studio的C#实例--2个窗体之间跳转
ide·c#·visual studio
荔枝吻1 小时前
【AI总结】C#与.NET:一段跨越20年的命名纠葛与共生传奇
开发语言·c#·.net
波波0072 小时前
每日一题:请解释 .NET中的内存模型是什么
开发语言·c#·.net
眼眸流转3 小时前
LeetCode热题100(七)
算法·leetcode·c#
格林威4 小时前
工业相机图像采集处理:从 RAW 数据到 AI 可读图像,附海康相机 C++实战代码
开发语言·c++·人工智能·数码相机·计算机视觉·c#·工业相机
需要点灵感4 小时前
# 从身份证读卡到钉钉同步:C# WinForms企业级应用开发实战
开发语言·c#·钉钉
SunnyDays10115 小时前
使用 C# 实现 Word 转 Excel并保留格式(只需三步)
c#·word 转 excel·docx转xlsx·doc转xlsx·word 表格转 excel
码路星河5 小时前
SpringBoot3实战:优雅实现Word文档动态生成与下载
开发语言·c#·word
Eiceblue5 小时前
通过 C# 读取 Word 表格数据:高效解析 + 导出为 CSV/TXT
开发语言·c#·word
格林威5 小时前
工业相机图像采集处理:从 RAW 数据到 AI 可读图像,堡盟相机 C#实战代码深度解析
c++·人工智能·数码相机·opencv·算法·计算机视觉·c#