C#基础知识之FileStream
一、FileStream的基础知识 属性: CanRead 判断当前流是否支持读取,返回bool值,True表示可以读取 方法: Read() 从流中读取数据,返回字节数组 文件的访问方式:(FileAccess) FileAccess.Read(对文件读访问) 文件打开模式:(FileMode)包括6个枚举 FileMode.Append 打开现有文件准备向文件追加数据,只能同FileAccess.Write一起使用 文件共享方式:(FileShare) FileShare方式是为了避免几个程序同时访问同一个文件会造成异常的情况。 文件共享方式包括四个: FileShare.None 谢绝共享当前文件 二、FileStream的异步操作 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; using System.Threading; namespace StreamWin { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender,EventArgs e) { string filePaths = @"E:TestTestlocala.txt"; string fileName ="a.txt" ; System.IO.FileInfo f = new FileInfo(@"E:TestTestservera.txt"); int fileLength = Convert.ToInt32(f.Length.ToString()); ThreadPool.SetMaxThreads(100,100); using (System.IO.FileStream stream = new System.IO.FileStream(filePaths,FileMode.Create,FileAccess.Write,FileShare.Write,1024,true)) { for (int i = 0; i < fileLength; i +=100 * 1024) { int length = (int)Math.Min(100 * 1024,fileLength - i); var bytes = GetFile(fileName,i,length); stream.BeginWrite(bytes,length,new AsyncCallback(Callback),stream); } stream.Flush(); } } public static byte[] GetFile(string name,int start,int length) { string filepath = @"E:TestTestservera.txt"; using (System.IO.FileStream fs = new System.IO.FileStream(filepath,System.IO.FileMode.Open,System.IO.FileAccess.Read,FileShare.ReadWrite,true)) { byte[] buffer = new byte[length]; fs.Position = start; fs.BeginRead(buffer,new AsyncCallback(Completed),fs); return buffer; } } static void Completed(IAsyncResult result) { FileStream fs = (FileStream)result.AsyncState; fs.EndRead(result); fs.Close(); } public static void Callback(IAsyncResult result) { FileStream stream = (FileStream)result.AsyncState; stream.EndWrite(result); stream.Close(); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |