C 檔案操作

2021-08-04 03:32:10 字數 2781 閱讀 2603

1、開啟檔案

public

static filestream open(string path,filemode mode)

使用方法

//開啟存放在c:\tempuploads目錄下名稱為newfile.txt檔案,並在該檔案中寫入hello      

byte info = ;

textfile.write(info,0,info.length);

textfile.close();

2、檔案的建立方法

public

static filestream create(string path)

使用方法

//在c:\tempuploads下建立名為newfile.txt的檔案

/*注意:由於file.create方法預設向所有使用者授予對新檔案的完全讀/寫訪問許可權,所以檔案是用讀/寫訪問許可權開啟的,必須關閉後才能由其他應用程式開啟。為此,所以需要使用filestream類的close方法將所建立的檔案關閉。*/

filestream newtext=file.create(@"c:\tempuploads\newfile.txt");

newtext.close();

3、檔案刪除方法

public

static

void

delete(string path);

使用方法

//刪除c:\tempuploads目錄下的newfile.txt檔案。

file.delete(@"c:\tempuploads\newfile.txt");

4、檔案的複製方法

public

static

void

copy(string sourcefilename,string destfilename,bool overwrite);

使用方法

/*將c:\tempuploads

\newfile.txt複製到

c:\tempuploads

\backup.txt*/

/*注:由於cope方法的overwrite引數設為true,所以如果backup.txt檔案已存在的話,將會被複製過去的檔案所覆蓋。*/

file.copy(@"c:\tempuploads

\newfile.txt",@"c:\tempuploads

\backup.txt",true);

5、檔案的移動

public

static

void

move(string sourcefilename,string destfilename);

使用方法

下面的**可以將c:\tempuploads下的backup.txt檔案移動到c盤根目錄下。

注意:只能在同乙個邏輯盤下進行檔案轉移。如果試圖將c盤下的檔案轉移到d盤,將發生錯誤。

file.move(@"c:\tempuploads\backup.txt",@"c:\backup.txt");
6、設定檔案的屬性

public

static

void

setattributes(string path,fileattributes fileattributes);

使用方法:

//下面的**可以設定檔案c:\tempuploads\newfile.txt的屬性為唯讀、隱藏。

//檔案除了常用的唯讀和隱藏屬性外,還有archive(檔案存檔狀態),system(系統檔案),temporary(臨時檔案)等

file.setattributes(@"c:\tempuploads\newfile.txt",

fileattributes.readonly|fileattributes.hidden);

7、判斷檔案是否存在

public

static

bool

exists(string path);

使用方法

file.exists(@"c:\tempuploads\newfile.txt")//判斷檔案是否存在
8、txt檔案操作

//讀檔案

streamreader txtreader = new streamreader(@"c:\tempuploads\newfile.txt",system.text

.encoding

.default);

string filecontent;

filecontent = txtreader.readend();

txtreader.close();

//寫檔案

streamwriter = new streamwrite(@"c:\tempuploads\newfile.txt",system.text

.encoding

.default);

string filecontent;

txtwriter.write(filecontent);

txtwriter.close();

C 檔案操作與C 的檔案操作

c filestream 檔案流 主要用於使用二進位制方式讀寫檔案資料,可讀取任何檔案 建立filestream物件 e 建立filestream物件 filemode 指定系統開啟檔案的方式filestream fileaccess 指定檔案的訪問方式 read唯讀,write只寫,readwri...

C 檔案操作

c 追加檔案 sw.writeline 追逐理想 sw.writeline kzlll sw.writeline net筆記 sw.flush sw.close c 拷貝檔案 string orignfile,newfile file.copy orignfile,newfile,true c 刪除...

C 檔案操作

c 檔案操作 軒軒 發表於 2006 2 18 12 40 16 在c 中,有乙個stream這個類,所有的i o都以這個 流 類為基礎的,包括我們要認識的檔案i o,stream這個類有兩個重要的運算子 1 插入器 向流輸出資料。比如說系統有乙個預設的標準輸出流 cout 一般情況下就是指的顯示器...