//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#創建目錄
//www.bianceng.cn
//創建目錄c:/sixAge
DirectoryInfod=Directory.CreateDirectory("c:/sixAge");
//d1指向c:/sixAge/sixAge1
DirectoryInfod1=d.CreateSubdirectory("sixAge1");
//d2指向c:sixAgesixAge1sixAge1_1
DirectoryInfod2=d1.CreateSubdirectory("sixAge1_1");
//將當前目錄設為c:/sixAge
Directory.SetCurrentDirectory("c:/sixAge");
//創建目錄c:/sixAge/sixAge2
Directory.CreateDirectory("sixAge2");
//創建目錄c:sixAgesixAge2sixAge2_1
Directory.CreateDirectory("sixAge2/sixAge2_1");
但是,在對txt文件讀的操作中貌似沒問題。因為代碼能實現文件的讀操作,但是所讀txt文件包含中文的時候就以亂碼顯示。查了半天資料,看似復雜的問題其實很簡單就能解決,稍微改動一下即可:
StreamReader sr = new StreamReader(fileName,Encoding.GetEncoding("gb2312"));