asp教程.net c寫檔案函數執行個體代碼
streamwriter 和 streamreader 向流寫入字元並從流讀取字元。下面的程式碼範例開啟 log.txt 檔案(如果檔案不存在則建立檔案)以進行輸入,並將資訊附加到檔案尾。然後將檔案的內容寫入標準輸出,以便顯示出來。
[c#]
using system;
using system.io;
class dirappend
{
public static void main(string[] args)
{
streamwriter w = file.appendtext("log.txt");
log ("test1", w);
log ("test2", w);
// close the writer and underlying file.
w.close();
// open and read the file.
streamreader r = file.opentext("log.txt");
dumplog (r);
}
public static void log (string logmessage, textwriter w)
{
w.write("rnlog entry : ");
w.writeline("{0} {1}", datetime.now.tolongtimestring(),
datetime.now.tolongdatestring());
w.writeline(" :");
w.writeline(" :{0}", logmessage);
w.writeline ("-------------------------------");
// update the underlying file.
w.flush();
}
public static void dumplog (streamreader r)
{
// while not at the end of the file, read and write lines.
string line;
while ((line=r.readline())!=null)
{
console.writeline(line);
}
r.close();
}
}
讀取檔案二
using (filestream fs = new filestream(file, filemode.open,fileaccess.readwrite))
{
xmldocument toxml = new xmldocument();
toxml.load(fs);
//do some modification for the xml.
fs.flush();
toxml.save(fs);
}
更多詳細內容請查看:http://www.111cn.net/net/c/33608.htm
讀取檔案三
寫檔案
public static void writefile(string filepath, string str)
{
streamwriter sr;
if (file.exists(filepath)) //如果檔案存在,則建立file.appendtext對象
{
sr = file.appendtext(filepath);
}
else //如果檔案不存在,則建立file.createtext對象
{
sr = file.createtext(filepath);
}
sr.writeline(str);
sr.close();
}