您的位置:首页 > 其它

FileStream 的文件读取与写入 之一(读写文件)

2013-05-24 02:03 197 查看
序言:FileStream 去读取文件和写文件比File有很大的优势,其中最重要的是当读取一个大文件时FileStream可以多次去读,而File就很难做到:

下面分别是写入问价和读取文件的方法:

========写入方法=======

// 首先选择一个要写入的文件

private void ChoseFilePath()

{

// 选择文件框对象

OpenFileDialog ofd = new OpenFileDialog();

// 设置默认文件路径

ofd.InitialDirectory = @"C:\Users\HP\Desktop";

// 如果用户选择了确定

if (ofd.ShowDialog() == DialogResult.OK)

{

txtFileName.Text = ofd.FileName;

}

}

// 写入到选择的文件中

private void SaveFile()

{

// 获取要保存的文件内容

string strContent = txtContent.Text.Trim();

// 创建文件流(文件路径、文件操作)

using (FileStream fs = new FileStream(txtFileName.Text, FileMode.Create))

{

//// 设置默认存储四兆大小的文件

//byte[] byteFile = new byte[1024*1024*4];

// 把文件(字符串)转换成字节数组(也有把字节转换成文件的方法)

byte[] byteFile = Encoding.UTF8.GetBytes(strContent);

// 往文件里写数据

fs.Write(byteFile, 0, byteFile.Length);

MessageBox.Show("保存成功");

}

}

========读取文件============

// 首先选择要读取的文件路径

private void ChoseReadFile()

{

OpenFileDialog ofd = new OpenFileDialog();

ofd.InitialDirectory = @"C:\Users\HP\Desktop";

if (ofd.ShowDialog() == DialogResult.OK)

{

txtReadFileName.Text = ofd.FileName;

}

}

// 读取文件

private void Read()

{

using(FileStream fs = new FileStream(txtReadFileName.Text,FileMode.Open))

{

byte[] byteData = new byte[1024*1024*4];

int length = fs.Read(byteData, 0, byteData.Length);

if (length > 0)

{

string strContent = Encoding.UTF8.GetString(byteData);

txtReadContent.Text = strContent;

}

}

}

注意:以上是简单的读取文件和写入文件的方法,并且指定了文件读取的大小。但是当读取的文件大时,肯定会报错的,后续我会总结一种循环读取大文件的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐