C#基本常識之FileStream。本站提示廣大學習愛好者:(C#基本常識之FileStream)文章只能為提供參考,不一定能成為您想要的結果。以下是C#基本常識之FileStream正文
1、FileStream的基本常識
屬性:
CanRead 斷定以後流能否支撐讀取,前往bool值,True表現可以讀取
CanWrite 斷定以後流能否支撐寫入,前往bool值,True表現可以寫入
辦法:
Read() 從流中讀取數據,前往字節數組
Write() 將字節塊(字節數組)寫入該流
Seek() 設置文件讀取或寫入的肇端地位
Flush() 消除該流緩沖區,使得一切緩沖的數據都被寫入到文件中
Close() 封閉以後流並釋放與之相干聯的一切體系資本
文件的拜訪方法:(FileAccess)
FileAccess.Read(對文件讀拜訪)
FileAccess.Write(對文件停止寫操作)
FileAccess.ReadWrite(對文件讀或寫操作)
文件翻開形式:(FileMode)包含6個列舉
FileMode.Append 翻開現有文件預備向文件追加數據,只能同FileAccess.Write一路應用
FileMode.Create 指導操作體系應創立新文件,假如文件曾經存在,它將被籠罩
FileMode.CreateNew 指導操作體系應創立新文件,假如文件曾經存在,將激發異常
FileMode.Open 指導操作體系應翻開現有文件,翻開的才能取決於FileAccess所指定的值
FileMode.OpenOrCreate 指導操作體系應翻開文件,假如文件不存在則創立新文件
FileMode.Truncate 指導操作體系應翻開現有文件,而且清空文件內容
文件同享方法:(FileShare)
FileShare方法是為了不幾個法式同時拜訪統一個文件會形成異常的情形。
文件同享方法包含四個:
FileShare.None 拒絕同享以後文件
FileShare.Read 充許其余法式讀取以後文件
FileShare.Write 充許其余法式寫以後文件
FileShare.ReadWrite 充許其余法式讀寫以後文
2、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:\Test\Test\local\a.txt";
string fileName ="a.txt" ;
System.IO.FileInfo f = new FileInfo(@"E:\Test\Test\server\a.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, 0, length, new AsyncCallback(Callback), stream);
}
stream.Flush();
}
}
public static byte[] GetFile(string name, int start, int length)
{
string filepath = @"E:\Test\Test\server\a.txt";
using (System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite,1024,true))
{
byte[] buffer = new byte[length];
fs.Position = start;
fs.BeginRead(buffer, 0, length,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();
}
}
}