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));
        }
    }
}

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

相关推荐
samble1 小时前
从零搭建灌装监控系统(十七):LiveCharts 实时温度曲线
c#·wpf·mvvm·modbus·工业控制
淡海水10 小时前
02-07-原理篇-GC暂停时间的本质
开发语言·unity·c#·gc·暂停时间
小羊没烦恼!11 小时前
OS X 上使用.NET开发应用程序
开发语言·前端·数据库·人工智能·c#·策略模式
Behavior13 小时前
Unity 7.0 Alpha 拆解:编辑器干掉 Mono 换 CoreCLR
c#·unity3d·游戏开发
淡海水13 小时前
02-06-原理篇-增量式GC与并发GC
算法·unity·c#·并发·gc·增量
Vertira14 小时前
C# 函数封装成 DLL,
开发语言·c#
浅尝辄止;15 小时前
设计模式在HIS/LIS医疗系统中的完整实践指南(C#版)
开发语言·设计模式·c#
kimloner1 天前
开源一个 376KB 的 Windows 桌面小工具:便签 + 截图标注 + OCR + 待办提醒(C# / WinForms)
windows·开源·c#·ocr·winforms
阿松爱学习1 天前
【Unity开发】Aspose.PDF的使用
unity·pdf·c#
半亩码田1 天前
C#转Python第4.8篇:正则表达式:Python re 模块 vs C# System.Text.RegularExpressions
python·正则表达式·c#