c#文件相关笔记
阅读原文时间:2023年07月13日阅读:1

1、将*.txt文件内容转换为一个字符串str

FileStream fs = new FileStream("路径\\*.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs,Encoding.Default);
string str = sr.ReadToEnd();

2、将str写入*.txt

string str = "";
FileStream fsWrite = new FileStream("路径\\*.txt", FileMode.OpenOrCreate, FileAccess.Write);

StreamWriter sw = new StreamWriter(fsWrite,Encoding.Default);

sw.WriteLine(str);   
sw.Close();

3、将str追加到*.txt

string str="";

StreamWriter sw =File.AppendTex("路径\\*.txt");

sw.WriteLine(str);   
sw.Close();

4、以文件流的方式打开或保存文件

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, , data.Length);  
            }  
        }  
    }