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

相关推荐
小老鼠爱大米2 小时前
[C#] WPF - 资源URI
c#·wpf·uri
阿蒙Amon9 天前
《C#图解教程 第5版》深度推荐
开发语言·c#
暖馒10 天前
C#委托与事件的区别
开发语言·c#
JosieBook10 天前
【C#】C#异步编程:异步延时 vs 阻塞延时深度对比
c#·多线程·异步·阻塞
甄天10 天前
WPF中MVVM和MVVMLight模式
c#·wpf·visual studio
冰茶_10 天前
ASP.NET Core API文档与测试实战指南
后端·学习·http·ui·c#·asp.net
_oP_i10 天前
实现 “WebView2 获取word选中内容
开发语言·c#·word
Kookoos10 天前
ABP vNext + Azure Application Insights:APM 监控与性能诊断最佳实践
后端·c#·.net·abp vnext
专注VB编程开发20年10 天前
asp.net core Razor动态语言编程代替asp.net .aspx更高级吗?
开发语言·后端·c#·asp.net·.net
安木夕10 天前
C#.Net筑基-优雅LINQ的查询艺术
c#·.net