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操作。

相关推荐
zybsjn15 分钟前
后端系统做国际化改造,生成多语言包
java·python·c#
敲代码的 蜡笔小新1 小时前
【行为型之迭代器模式】游戏开发实战——Unity高效集合遍历与场景管理的架构精髓
unity·设计模式·c#·迭代器模式
yc_12242 小时前
SqlHelper 实现类,支持多数据库,提供异步操作、自动重试、事务、存储过程、分页、缓存等功能。
数据库·c#
Kookoos2 小时前
Redis + ABP vNext 构建分布式高可用缓存架构
redis·分布式·缓存·架构·c#·.net
Zhen (Evan) Wang4 小时前
ABP-Book Store Application中文讲解 - Part 2: The Book List Page
c#
小乖兽技术6 小时前
在 .NET 8 开发的WinForms 程序中展示程序版本号的几种方式
开发语言·c#·.net
TheWindofFate6 小时前
C# 基础 try-catch代码块
c#·try-catch
TIF星空10 小时前
【使用 C# 获取 USB 设备信息及进行通信】
开发语言·经验分享·笔记·学习·microsoft·c#
csdn_aspnet12 小时前
如何在 C# 中自定义 Datagridview 标题
c#·winform·datagridview
津津有味道12 小时前
MIFARE DESFire Light 卡C#读写更改卡片密钥源码
c#·light·desfire·ev2