一、將*.txt文件內容轉換爲一個字符串strspa
FileStream fs = new FileStream("路徑\\*.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs,Encoding.Default);
string str = sr.ReadToEnd();code
二、將str寫入*.txtblog
string str = "";
FileStream fsWrite = new FileStream("路徑\\*.txt", FileMode.OpenOrCreate, FileAccess.Write);字符串
StreamWriter sw = new StreamWriter(fsWrite,Encoding.Default);string
sw.WriteLine(str);
sw.Close();it
三、將str追加到*.txtclass
string str="";object
StreamWriter sw =File.AppendTex("路徑\\*.txt");coding
sw.WriteLine(str);
sw.Close();im
四、以文件流的方式打開或保存文件
private void btSelect_Click(object sender, EventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog()) { if (ofd.ShowDialog() != DialogResult.OK) { return; } //讀文件 //string strRead= File.ReadAllText(ofd.FileName, Encoding.Default); //小文件 using (FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { while (!sr.EndOfStream) { string strLine = sr.ReadLine(); rbRead.Text += strLine; } } } } }
private void btSave_Click(object sender, EventArgs e) { using (SaveFileDialog sfd = new SaveFileDialog()) { if (sfd.ShowDialog() != DialogResult.OK) { return; } //File.WriteAllText(sfd.FileName,rbWrite.Text); //小文件 //using (StreamWriter sw = new StreamWriter(sfd.FileName, false, Encoding.Default, 1024 * 1024)) //{ // sw.Write(rbWrite.Text); // sw.Flush(); //} using (FileStream fs = new FileStream(sfd.FileName, FileMode.OpenOrCreate, FileAccess.Write)) { string str=rbWrite.Text; byte[] data=Encoding.Default.GetBytes(str); fs.Write(data, 0, data.Length); } } }