目的:txt文件的创建,读写操作
功能:创建一个winform窗体,当文件不存在时可以实现txt文件的创建
效果:
代码:
文件的创建(判断文件是否存在,不存在则创建新的文本文件):
private void btnCreate_Click(object sender, EventArgs e) { FileStream fs = new FileStream(_path, FileMode.OpenOrCreate); fs.Close(); }
数据读取:
private void btnRead_Click(object sender, EventArgs e) { if (File.Exists(_path)) { txtInfo.Text = ""; string[] info = File.ReadAllLines(_path, Encoding.Default); ; i < info.Length; i++) { txtInfo.Text += info[i] + "\r\n"; } } else { MessageBox.Show("文件不存在!","提示"); } }
数据写入:
private void btnWrite_Click(object sender, EventArgs e) { FileStream fs = new FileStream(_path, FileMode.Append); StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("GBK")); sw.Write(txtWrite.Text+"\r\n"); sw.Flush(); sw.Close(); fs.Close(); }
注:
string _path = Application.StartupPath + @"\"+System.DateTime.Now.ToString("yyyyMMdd")+".txt";
代码下载:
http://download.csdn.net/detail/u010312811/9421107