---
title: "C#里的文件流(FileStream)"
author: "孙海友"
date: "2013-10-10T01:44:44Z"
tags: ["C#", "IO", "filestream"]
categories: ["编程语言"]
slug: "c-filestream"
draft: false
lastmod: "2013-10-10T01:49:43Z"
id: 1954028
url: "https://770736680.iteye.com/blog/1954028"
---

C#里的文件流(FileStream)

一、文件流（FileStream）

FileStream 类是公开以文件为主的 Stream，既支持同步读写操作，也支持异步读写操作。

命名空间:System.IO

程序集:mscorlib（在 mscorlib.dll 中）

 

在C#中的声明为

```
[ComVisibleAttribute(true)]
public class FileStream : Stream
```

 

二、文件流写入

 

```
 private void btnChooseOpenFile_Click(object sender, EventArgs e)
        {
            //选择文本框 对象
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = @"C:\Users\John\Desktop";
            //如果用户确定
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //将用户选择的文件路径显示在文本框上
                txtFilePathOpen.Text = ofd.FileName;
            }
        }

        //保存文件
        private void btnSave_Click(object sender, EventArgs e)
        {
            string strContent = txtInputSave.Text.Trim();
            //创建文件流(文件路径，文件操作、创建)
            using (FileStream fs = new FileStream(txtFilePathOpen.Text, FileMode.Create))
            {
                //将字符串字符串转成byte数组
                byte[] byteFile = Encoding.UTF8.GetBytes(strContent);
                //参数：要写到文件的数据数组，从第几个开始写，一共写多少个
                fs.Write(byteFile, 0, byteFile.Length);
                MessageBox.Show("保存成功！");
            }
        }
```

 

 

 

二、文件流读出

 

 

 

```
private void btnChooseOpenFile2_Click(object sender, EventArgs e)
        {
            //选择文本框 对象
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = @"C:\Users\John\Desktop";
            //如果用户确定
            if (ofd.ShowDialog() == DialogResult.OK) 
            {
                //将用户选择的文件路径显示在文本框上
                txtFilePathOpen2.Text = ofd.FileName;
            }
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            using (FileStream fs = new FileStream(txtFilePathOpen2.Text, FileMode.Open))
            {
                byte[] byteData = new byte[1024 * 1024 * 4];
                //返回读取的长度
                int length=fs.Read(byteData,0,byteData.Length);
                if (length > 0) 
                {
                    string strData = Encoding.UTF8.GetString(byteData);
                    txtOutputRead.Text = strData;
                    MessageBox.Show("读取成功");
                }
            }
        }
```

 

四、结果：

 ![](http://dl2.iteye.com/upload/attachment/0089/9998/70042e57-6613-36f8-b582-088f9f2dbecd.jpg)

说明：FileStream将文件中的数据以字节地方式读出(Read)或写入(Write)

当我们需要使用文件流时，需要Encoding.UTF8.GetBytes(strContent);

当我们需要显示时，需要：Encoding.UTF8.GetString(byteData);

C#中的FileStream封装的比较好，比较简单。

FileStream同样可以在C++,J#,VB,JS等当中使用。

本博客中的例子是FileStream在WinForm程序中的简单应用，代码在附件中哦！