本章講述:filestream類的基本功能,以及簡單示例;
1、引用命名空間:using system.io;
2、注意:使用io操作檔案時,要注意流關閉和釋放問題!
強力推薦:將建立檔案流物件的過程寫在using當中,會自動幫助我們釋放資源;
使用try{} catch(exception ex){} 進行一次捕獲;
3、filestream 操作位元組,可以操作任何型別的檔案;下面來簡單介紹filestream類的方法和引數:
(1)filestream() 作用:建立filestream物件,引數:第乙個是路徑,第二個是檔案模式filemode列舉,第三個資料模式fileacess
初始化filestream時使用包含檔案共享屬性(system.io.fileshare)的建構函式比使用自定義執行緒鎖更為安全和高效
filestream(string, filemode):
filestream(string, filemode, fileaccess)
filestream(string, filemode, fileaccess, fileshare)
filestream(string, filemode, fileaccess, fileshare, int32)
(3)fileacess(檔案流物件如何訪問該檔案):read(唯讀) 、write(寫)、readwirte(讀寫);
(4)fileshare(程序如何共享檔案):none(拒絕共享)、read 、write、readwrite(同時讀寫)、delete;
(5)buffersize(緩衝區大小設定)
4、stream.read(array5、stream.write(array6、close():關閉當前流並釋放與當前流關聯的任何資源(如套接字和檔案控制代碼);
7、dispose():釋放流所有使用的資源;
8、copyto(stream):從當前流中讀取所有位元組並將其寫入目標流。
copyto(stream, int32):從當前流中讀取所有位元組,並使用指定的緩衝區大小將它們寫入目標流
9、seek()(filestream類維護內部檔案指標,該指標指向檔案中進行下一次讀寫操作的位置):將此流的當前位置設定為給定值。(stream.seek(int64,seekorigin)
第乙個引數規定檔案指標以位元組為單位的移動距離。第二個引數規定開始計算的起始位置;seekorigin列舉包含3個值:begin、current 和 end;
例如:afile.seek(0, seekorigin.end);
10、由於設定了檔案共享模式為允許隨後寫入,所以即使多個執行緒同時寫入檔案,也會等待之前的執行緒寫入結束之後再執行,而不會出現錯誤
using (filestream logfile = new filestream(logfilepath, filemode.openorcreate, fileaccess.write, fileshare.write))
11、簡單示例1:簡單檔案寫入
12、簡單示例2:以追加的方式寫入檔案
filestream devstream =
512);
devstream.write(data,
0, 128);
if(devstream !=
null)
devstream.close();
13、簡單示例:檔案流寫入
public
static
class
monitdata}}
} }
}
14、簡單示例:讀取檔案
public
static
void
main(string args)}}
sw.stop();
console.writeline(
"總的執行時間為",sw.elapsedmilliseconds);
console.readkey();
}
public
static
string
filestreamreadfile(string filepath)
本章講述:filestream類的基本功能,以及簡單示例;
C FileStream複製大檔案
即每次複製檔案的一小段,以節省總記憶體開銷。當然,本機複製也可以採用.net內部的system.io.file.copy方法。複製檔案 要複製的檔案 要儲存的位置 每次複製的長度 private void copyfile string fromfile,string tofile,int leng...
C FileStream與Stream類區別
學習流的使用時 stream類 逐步遇到新的理解,記錄一下 1 filestream流是處理byte,預設utf8型別 當你使用wirte方法時將非byte型別的輸入內容,先將內容通過轉換為位元組 filestream fs new filestream c text.txt filemode.cr...
C FileStream 物件的Seek()方法
2010年12月08日 11 22 00 kevin617 閱讀數 7565 filestream 可以隨機讀寫檔案 使用 seek 方法 seek 有兩個引數 第一引數規定檔案指標以位元組為單位移動的距離。第二個引數規定開始計算的位置 用 seekorigin 列舉的乙個值表示 seekorigi...