C 判斷檔案是否存在和檔案讀寫

2021-07-27 22:09:01 字數 1328 閱讀 5318

一、檔案是否存在

c#中操作io非常簡單,下面介紹如何判斷資料夾或檔案是否存在的方法。  **如下: 

//判斷資料夾是否存在,不存在則建立資料夾 

if (!system.io.directory.exists(@"e:\files")) 

//判斷某檔案是否存在 

需要引用命名空間using system.io; 

if(file.exists(@"e:\files\test.txt")) 

else 

二、檔案讀寫

檔案寫

class writetextfile

;system.io.file.writealllines(@"c:\testdir\test.txt", lines, encoding.utf8);

//如果檔案不存在,則建立;存在則覆蓋

string strtest = "該例子測試乙個字串寫入文字檔案。";

system.io.file.writealltext(@"c:\testdir\test1.txt", strtest, encoding.utf8);

//在將文字寫入檔案前,處理文字行

//streamwriter乙個引數預設覆蓋

//streamwriter第二個引數為false覆蓋現有檔案,為true則把文字追加到檔案末尾

using (system.io.streamwriter file = new system.io.streamwriter(@"c:\testdir\test2.txt",true))}}

}}

檔案讀

class readtextfile

//從頭到尾以流的方式讀出文字檔案

//該方法會一行一行讀出文字

using (system.io.streamreader sr = new system.io.streamreader(@"c:\testdir\test.txt"))

}console.read();

}}

三、讀取內容string轉int等

例string linesread = file.readalllines(@strconfigpath);

convert.toint32(linesread[0]);

to其他格式的可以轉別的資料型別

四、system.io.ioexception

msdn闡述:如果發生 i/o 錯誤(如讀寫檔案失敗),則會引發 ioexception。

目前遇到的問題,以上讀寫方法有的貌似不會自動關閉檔案流,手動開啟讀寫用的測試檔案後,會出現該異常

如何處理留待更新

GO 檔案讀寫 判斷檔案是否存在

很簡單寫乙個簡單的案例即可 在之前的案例已經學習過了go的函式,那麼在這裡就簡單的使用一下 還是需要多寫,咔咔之前是寫php的,現在開始go發現go的語法很美啊!對go已經上癮了 這個案例很是簡單,主要就是乙個函式的返回值,在函式的後邊可以定義返回值,也可以不用定義,只需要定義返回型別也行。然後在函...

C 判斷檔案是否存在

用函式access,標頭檔案是io.h,原型 int access const char filename,int amode amode引數為0時表示檢查檔案的存在性,如果檔案存在,返回0,不存在,返回 1。這個函式還可以檢查其它檔案屬性 06 檢查讀寫許可權 04 檢查讀許可權 02 檢查寫許可...

python判斷檔案和資料夾是否存在 建立資料夾

python中對檔案 資料夾的操作需要涉及到os模組和shutil模組。1 os.mknod test.txt 建立空檔案 2 open test.txt w 直接開啟乙個檔案,如果檔案不存在則建立檔案 os.mkdir file 建立目錄 shutil.copyfile oldfile newfi...