码迷,mamicode.com
首页 > Windows程序 > 详细

C#操作txt文件

时间:2016-01-28 15:23:03      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

目的:txt文件的创建,读写操作

功能:创建一个winform窗体,当文件不存在时可以实现txt文件的创建

效果:

技术分享

 

 

代码:

文件的创建(判断文件是否存在,不存在则创建新的文本文件):

1    private void btnCreate_Click(object sender, EventArgs e)
2    {
3        FileStream fs = new FileStream(_path, FileMode.OpenOrCreate);
4        fs.Close();
5    }

 

数据读取:

 1    private void btnRead_Click(object sender, EventArgs e)
 2    {
 3        if (File.Exists(_path))
 4        {
 5            txtInfo.Text = "";
 6            string[] info = File.ReadAllLines(_path, Encoding.Default);
 7            for (int i = 0; i < info.Length; i++)
 8            {
 9                txtInfo.Text += info[i] + "\r\n";
10            }
11        }
12        else
13        {
14            MessageBox.Show("文件不存在!","提示");
15        }
16    }

数据写入:

 

1    private void btnWrite_Click(object sender, EventArgs e)
2    {
3        FileStream fs = new FileStream(_path, FileMode.Append);
4        StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("GBK"));
5        sw.Write(txtWrite.Text+"\r\n");
6        sw.Flush();
7        sw.Close();
8        fs.Close();
9    }

 

C#操作txt文件

标签:

原文地址:http://www.cnblogs.com/imstrive/p/5166248.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!