读取文本文件:
public string GetTxtContents(string file)
...{
StringBuilder allText = new StringBuilder();
StreamReader sr = null;
try
...{
sr = new StreamReader(file,System.Text.Encoding.GetEncoding("gb2312"));
string lineText;
do
...{
lineText = sr.ReadLine();
if(lineText != "")
...{
allText.Append(lineText + " ");
}
}while(sr.Peek()!=-1);
}
catch(Exception fileExp)
...{
throw new Exception("读取文件信息失败,系统信息:" + fileExp.Message);
}
finally
...{
sr.Close();
}
return allText.ToString();
}
写入文本文件:
private void button2_Click(object sender, System.EventArgs e)
...{
string content = this.richTextBox1.Text;
string file = this.textBox1.Text;
StreamWriter sw = null;
sw = File.CreateText(file);
sw.WriteLine(content);
sw.Flush();
sw.Close();
MessageBox.Show("写入文件成功!");
try 
...{
StreamWriter writer=null;
string file = this.textBox1.Text;
string content = this.richTextBox1.Text;
if (File.Exists(filePath)) 
...{
writer=File.AppendText(file);
}
else 
...{
writer=File.CreateText(file);
}
writer.WriteLine(content);
writer.Close();
}
catch (Exception fileExp) 
...{
throw new Exception("写入文件信息失败,系统信息:" + fileExp.Message);
}
}
这篇博客详细介绍了如何使用C#进行文本文件的读取和写入操作。通过示例代码,展示了如何打开、读取文件内容,以及如何将数据写入新的或已存在的文本文件中,同时涵盖了异常处理和文件操作的基本注意事项。

709

被折叠的 条评论
为什么被折叠?



