C#基础
关于Filestream的运用。
概念:Filestream 可对文本进行读也可以对多媒体文件进行写,以字节组的形式进行读写,多用于对文件进行读写。缺点在于需要手动的关闭和释放资源。
FileStream(string path,FileMode.mode, FileAccess.Read)
path:当前Filestream对象将封装的文件的相对路径或绝对路径。
mode:一个常数,用于确定如何打开或者创建文件。
access:一个常数,用于确定filestream对象访问文件的形式。
例如:创建一个读写文件winform程式,并显示读写进度。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace FileStream运用
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//显示一个标准的对话框,提示用户需要打开的文件
OpenFileDialog ofd = new OpenFileDialog();
//对话框的标题
ofd.Title = "请选择需要复制的文件";
//获取对话框显示的初始目录
ofd.InitialDirectory = @"C:\Users\A804G012\Desktop";
//获取对话框中文件的显示类型
ofd.Filter = "所有文件|*.*";
ofd.ShowDialog();
//将对话框的文件名复制到TextBox中
TxtUpload.Text = ofd.FileName;
}
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog Sfd = new SaveFileDialog();
Sfd.Title = "请选择需要保存的文件";
Sfd.InitialDirectory = @"C:\Users\A804G012\Desktop";
Sfd.Filter = "所有文件|*.*";
Sfd.ShowDialog();
TxtSave.Text = Sfd.FileName;
using (FileStream fsread = new FileStream(TxtUpload.Text.Trim(), FileMode.OpenOrCreate, FileAccess.Read))
{
using (FileStream fswrite = new FileStream(TxtSave.Text.Trim(), FileMode.OpenOrCreate, FileAccess.Write))
{
//进度条最长的值
this.progressBar1.Maximum =(int) fsread.Length;
byte[] buffer = new byte[1024 * 1024 * 3];
while (true)
{
int r = fsread.Read(buffer,0,buffer.Length);
if (r == 0)
{
break;
}
this.progressBar1.Value = (int)fswrite.Length;
fswrite.Write(buffer,0,r);
}
}
}
}
}
}