FileStream的讀取和寫入

2021-07-27 14:10:37 字數 1957 閱讀 7591

使用 

filestream 類對檔案系統上的檔案進行讀取、寫入、開啟和關閉操作,並對其他與檔案相關的作業系統控制代碼進行操作,如管道、標準輸入和標準輸出。讀寫操作可以指定為同步或非同步操作。

filestream 對輸入輸出進行緩衝,從而提高效能。

先看**,後面講解:

using

system;

using

system.collections.generic;

using

system.componentmodel;

using

system.data;

using

system.drawing;

using

system.linq;

using

system.text;

using

system.windows.forms;

using

system.io;

//注意,必不可少

namespace

wasteindustry 

private

void

form3_load(

object

sender, eventargs e) 

//向流中寫入陣列內容

myfilestream1.write(mywritebytearray,

0,numberofbytestowrite);

//關閉流

myfilestream1.close();

//關閉流

myfilestream2.close();}}

} myfilestream1物件,使用指定路徑和建立模式例項化,建立模式filemode是乙個列舉型別,它還包括:

create

建立新檔案,如果檔案存在則覆蓋,沒有則新建

createnew

建立新檔案,有的話,出現異常

open

開啟現有的檔案,如果有開啟,不存在檔案就會引發異常

如果存在檔案則開啟,不存在則建立

如果存在檔案則開啟,不存在則建立

myfilestream2物件,用fileinfo例項化,fileinfo方法有open,openreade,opentext,create,createtext。

檔案流的讀取(read)與寫入(write);

read

//定義陣列長度

intnumberofbytes =20

;//byte型別陣列

byte

mybytearray 

=new

byte

[numberofbytes];

//從檔案中讀取20個位元組放入陣列中

intbytesread 

=myfilestream1.read(mybytearray,

0,numberofbytes);

定義乙個byte型別的陣列,設定陣列的長度,read方法就是在檔案中從0開始讀取,讀取20個位元組數,然後替換到陣列中

//定義陣列長度

intnumberofbytestowrite 

=256;//

定義byte型別陣列

byte

mywritebytearray

=new

byte[numberofbytestowrite];

//迴圈向byte型別的陣列中插入byte值

for(

inti =0

; i 

<

256; i

++) 

//向流中寫入陣列內容

myfilestream1.write(mywritebytearray,

0,numberofbytestowrite);

定義乙個byte型別的陣列,設定陣列的長度,並通過迴圈想byte陣列中寫入位元組,通過write方法把陣列中的值從0位置開始向流中寫入內容;

FileStream的讀取和寫入

使用filestream類對檔案系統上的檔案進行讀取 寫入 開啟和關閉操作,並對其他與檔案相關的作業系統控制代碼進行操作,如管道 標準輸入和標準輸出。讀寫操作可以指定為同步或非同步操作。filestream對輸入輸出進行緩衝,從而提高效能。先看 後面講解 using system using sys...

使用FileStream來讀取資料

using system using system.collections.generic using system.io using system.linq using system.text using system.threading.tasks namespace listlistchar ...

C 分塊讀取文字資料(FileStream)

針對文字內容很大的時候,分塊來處理資料。直接上 using system.io using system.text static void readstreamfromfile while tempcount readcount catch finally 其中 stream.read buffer...