c#中流操作之一:Stream对象

(一)流的概述

流代表源与目标之间传输的一定的数据量。无论是文件、网络还是打印机等设备,流都要提供一种通用的方式与数据进行交互。流不仅可以访问文件,还可以访问网络、内存地址等。

可以看到,FileStream和MemoryStream都是直接继承于Stream抽象类。流继承于 System.IO.Stream抽象类,Stream的常用成员包括:

CanRead/CanWrite/CanSeek

Close()

Flush()

FlushAsync()

Length

Position

CopyTo(Stream)

CopyTo(Stream,Int32)

CopyToAsync(Stream,Int32)

CopyToAsync(Stream,Int32,CancellationToken)

Read(byte[],int,int)

ReadAsync(byte[],int,int,CancellationToken)

ReadAsync(byte[],int,int)

ReadByte()

Synchronized(Stream)在指定的Stream对象周围创建线程安全(同步)包装

Seek(Int64,SeekOrigin)

SetLength(Int64)

Write(byte[],int,int)

WriteAsync(byte[],int,int)

WriteAsync(Byte[],int,int,CancellationToken)

WriteByte(Byte)

(二)常用的流实现类

2.1 FileStream

System.IO.FileStream直接从Stream派生而来。可以使用File.Create(fileFullPath),File.OpenRead(path),File.Open(path,FileMode),

File.OpenWrite(string path[,System.IO.FileMode mode]),File.OpenWrite(path)等方法来获得FileStream对象。

官方文档中的例子:

   using (FileStream fs = File.Create(path))
        {
            AddText(fs, "This is some text");
            AddText(fs, "This is some more text,");
            AddText(fs, "\r\nand this is on a new line");
            AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");

            for (int i=1;i < 120;i++)
            {
                AddText(fs, Convert.ToChar(i).ToString());
            }
        }
        using (FileStream fs = File.OpenRead(path))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
            while (fs.Read(b,0,b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    private static void AddText(FileStream fs, string value)
    {
        byte[] info = new UTF8Encoding(true).GetBytes(value);
        fs.Write(info, 0, info.Length);
    }

   private async void Button_Click(object sender, RoutedEventArgs e)
        {
            UnicodeEncoding uniencoding = new UnicodeEncoding();
            string filename = @"c:\Users\exampleuser\Documents\userinputlog.txt";

            byte[] result = uniencoding.GetBytes(UserInput.Text);

            using (FileStream SourceStream = File.Open(filename, FileMode.OpenOrCreate))
            {
                SourceStream.Seek(0, SeekOrigin.End);
                //using中调用异步方法,使用await挂起调用线程指导任务完成
                await SourceStream.WriteAsync(result, 0, result.Length);
            }
        }

2.2 MemoryStream

继承关系Object->MarshalByRefObject->Stream->MemoryStream

构造方法如下:即可以通过给定初始字节数组或初始容量来构造MemoryStream实例。

 

官方给出的使用案例如下:

  static void Main()
    {
        int count;
        byte[] byteArray;
        char[] charArray;
        UnicodeEncoding uniEncoding = new UnicodeEncoding();

        // Create the data to write to the stream.
        byte[] firstString = uniEncoding.GetBytes(
            "Invalid file path characters are: ");
        byte[] secondString = uniEncoding.GetBytes(
            Path.GetInvalidPathChars());

        using(MemoryStream memStream = new MemoryStream(100))
        {
            // Write the first string to the stream.
            memStream.Write(firstString, 0 , firstString.Length);

            // Write the second string to the stream, byte by byte.
            count = 0;
            while(count < secondString.Length)
            {
                memStream.WriteByte(secondString[count++]);
            }

            // Write the stream properties to the console.
            Console.WriteLine(
                "Capacity = {0}, Length = {1}, Position = {2}\n",
                memStream.Capacity.ToString(),
                memStream.Length.ToString(),
                memStream.Position.ToString());

            // Set the position to the beginning of the stream.
            memStream.Seek(0, SeekOrigin.Begin);

            // Read the first 20 bytes from the stream.
            byteArray = new byte[memStream.Length];
            count = memStream.Read(byteArray, 0, 20);

            // Read the remaining bytes, byte by byte.
            while(count < memStream.Length)
            {
                byteArray[count++] =
                    Convert.ToByte(memStream.ReadByte());
            }

            // Decode the byte array into a char array
            // and write it to the console.
            charArray = new char[uniEncoding.GetCharCount(
                byteArray, 0, count)];
            uniEncoding.GetDecoder().GetChars(
                byteArray, 0, count, charArray, 0);
            Console.WriteLine(charArray);
        }
    }

2.3 NetworkStream

官方文档中的例子

// Examples for constructors that do not specify file permission.

// Create the NetworkStream for communicating with the remote host.
NetworkStream myNetworkStream;

if (networkStreamOwnsSocket){
     myNetworkStream = new NetworkStream(mySocket, true);
}
else{
     myNetworkStream = new NetworkStream(mySocket);
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1.1 什么是Stream? 1.2 什么是字节序列? 1.3 Stream的构造函数 1.4 Stream的重要属性及方法 1.5 Stream的示例 1.6 Stream异步读写 1.7 Stream 和其子类的类图 2.1 为什么要介绍 TextReader? 2.2 TextReader的常用属性和方法 2.3 TextReader 示例 2.4 从StreamReader想到多态 2.5 简单介绍下Encoding 编码 2.6 StreamReader 的定义及作用 2.7 StreamReader 类的常用方法属性 2.8 StreamReader示例 3.1 为何介绍TextWriter? 3.2 TextWriter的构造,常用属性和方法 3.3 IFormatProvider的简单介绍 3.4 如何理解StreamWriter? 3.5 StreamWriter属性 3.6 StreamWriter示例 4.1 如何去理解FileStream? 4.2 FileStream的重要性 4.3 FileStream常用构造函数(重要) 4.4 非托管参数SafeFileHandle简单介绍 4.5 FileStream常用属性介绍 4.6 FileStream常用方法介绍 4.7 FileStream示例1:*文件的新建和拷贝(主要演示文件同步和异步操作) 4.8 FileStream示例2:*实现文件本地分段上传 5.1 简单介绍一下MemoryStream 5.2 MemoryStream和FileStream的区别 5.3 通过部分源码深入了解下MemoryStream 5.4 分析MemorySteam最常见的OutOfMemory异常 5.5 MemoryStream 的构造 5.6 MemoryStream 的属性 5.7 MemoryStream 的方法 5.8 MemoryStream 简单示例 : XmlWriter中使用MemoryStream 5.9 MemoryStream 简单示例 :自定义一个处理图片的HttpHandler 6.1 简单介绍一下BufferedStream 6.2 如何理解缓冲区? 6.3 BufferedStream的优势 6.4 从BufferedStream 中学习装饰模式 6.5 如何理解装饰模式 6.6 再次理解下装饰模式在Stream中的作用 6.7 BufferedStream的构造 6.8 BufferedStream的属性 6.9 BufferedStream的方法 6.10 简单示例:利用socket 读取网页并保存在本地 7.1 NetworkStream的作用 7.2 简单介绍下TCP/IP 协议和相关层次 7.3 简单说明下 TCP和UDP的区别 7.4 简单介绍下套接字(Socket)的概念 7.5 简单介绍下TcpClient,TcpListener,IPEndPoint类的作用 7.6 使用NetworkStream的注意事项和局限性 7.7 NetworkStream的构造 7.8 NetworkStream的属性 7.9 NetworkStream的方法 7.10 NetwrokStream的简单示例 7.11 创建一个客户端向服务端传输图片的小示例 版权归作者所有,仅供学习参考

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值