和Java一樣C#提供的類庫能夠輕松實現對文件的操作下面就給出代碼示例大家可以參考一下
//C#寫入/讀出文本文件
string fileName =@
c:I
txt
;
StreamReader sr = new StreamReader(fileName); string str=sr
ReadLine (); sr
close();
StreamWriterrw=File
CreateText(Server
MapPath(
)+
/myText
txt
);
rw
WriteLine(
寫入
);
rw
WriteLine(
abc
);
rw
WriteLine(
NET筆記
);
rw
Flush();
rw
Close();
//打開文本文件
StreamReadersr=File
OpenText(Server
MapPath(
)+
/myText
txt
);
StringBuilderoutput=newStringBuilder();
stringrl;
while((rl=sr
ReadLine())!=null)
{
output
Append(rl+
);
}
lblFile
Text=output
ToString();
sr
Close();
//C#追加文件
StreamWritersw=File
AppendText(Server
MapPath(
)+
/myText
txt
);
sw
WriteLine(
追逐理想
);
sw
WriteLine(
kzlll
);
sw
WriteLine(
NET筆記
);
sw
Flush();
sw
Close();
//C#拷貝文件
stringOrignFile
NewFile;
OrignFile=Server
MapPath(
)+
/myText
txt
;
NewFile=Server
MapPath(
)+
/myTextCopy
txt
;
File
Copy(OrignFile
NewFile
true);
//C#刪除文件
stringdelFile=Server
MapPath(
)+
/myTextCopy
txt
;
File
Delete(delFile);
//C#移動文件
stringOrignFile
NewFile;
OrignFile=Server
MapPath(
)+
/myText
txt
;
NewFile=Server
MapPath(
)+
/myTextCopy
txt
;
File
Move(OrignFile
NewFile);
//C#創建目錄
//創建目錄c:sixAge
DirectoryInfod=Directory
CreateDirectory(
c:/sixAge
);
//d
指向c:sixAgesixAge
DirectoryInfod
=d
CreateSubdirectory(
sixAge
);
//d
指向c:sixAgesixAge
sixAge
_
DirectoryInfod
=d
CreateSubdirectory(
sixAge
_
);
//將當前目錄設為c:sixAge
Directory
SetCurrentDirectory(
c:/sixAge
);
//創建目錄c:sixAgesixAge
Directory
CreateDirectory(
sixAge
);
//創建目錄c:sixAgesixAge
sixAge
_
Directory
CreateDirectory(
sixAge
/sixAge
_
);
但是在對txt文件讀的操作中貌似沒問題因為代碼能實現文件的讀操作但是所讀txt文件包含中文的時候就以亂碼顯示查了半天資料看似復雜的問題其實很簡單就能解決稍微改動一下即可
StreamReader sr = new StreamReader(fileName
Encoding
GetEncoding(
gb
));
From:http://tw.wingwit.com/Article/program/net/201311/14661.html