//保存路径
private void btnsavepath_Click(object sender, EventArgs e)
{
//实例化一个保存文件对话框
SaveFileDialog sf = new SaveFileDialog();
//设置文件保存类型
sf.Filter = "txt文件|*.txt";
//如果用户没有输入扩展名,自动追加后缀
sf.AddExtension = true;
//设置标题
sf.Title = "写文件";
//如果用户点击了保存按钮
if (sf.ShowDialog() == DialogResult.OK)
{
//实例化一个文件流--->与写入文件相关联
FileStream fs = new FileStream(sf.FileName, FileMode.Create);
//实例化一个输出流-->与fs相关联
StreamWriter sw = new StreamWriter(fs);
//开始写入
if (this.dataGridView1.Rows.Count < 1)//没有数据
{
MessageBox.Show("没有数据!导出失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
//因为DataGridView最后一行为空,所以减一
sw.WriteLine(this.dataGridView1.Rows.Count - 1);
for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
//如果某一列数据为空,就写入"",因为空对象不能调用tostring();
if (this.dataGridView1.Rows[i].Cells[j].Value != null)
sw.WriteLine(this.dataGridView1.Rows[i].Cells[j].Value.ToString());
//else
// sw.WriteLine("");//所有行数都有数据时隐去,若保存中有空行,则使用
}
}
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
MessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
//读取路径
private void btnreadpath_Click(object sender, EventArgs e)
{
//读取文件前先清除内容
for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
this.dataGridView1.Rows[i].Cells[j].Value = null;
}
}
//实例化一个保存文件对话框
OpenFileDialog sf = new OpenFileDialog();
//设置文件保存类型
sf.Filter = "txt文件|*.txt";
//如果用户没有输入扩展名,自动追加后缀
sf.AddExtension = true;
//设置标题
sf.Title = "读文件";
//如果用户点击了保存按钮
if (sf.ShowDialog() == DialogResult.OK)
{
//实例化一个文件流--->与写入文件相关联
FileStream fs = new FileStream(sf.FileName, FileMode.Open);
//实例化一个StreamWriter-->与fs相关联
StreamReader sw = new StreamReader(fs);
//开始读取
if (this.dataGridView1.Rows.Count < 1)
{
MessageBox.Show("没有数据!读取失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
int RowCount = int.Parse(sw.ReadLine());
//判断如果当前行数大于要读取的行数,就不add行,否则add行
if (RowCount <= this.dataGridView1.Rows.Count)//|| RowCount == this.dataGridView1.Rows.Count
{
for (int i = 0; i < RowCount; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
this.dataGridView1.Rows[i].Cells[j].Value = sw.ReadLine();
}
}
}
else
{
for (int i = 0; i < RowCount; i++)
{
this.dataGridView1.Rows.Add();
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
this.dataGridView1.Rows[i].Cells[j].Value = sw.ReadLine();
}
}
}
//关闭流
sw.Close();
fs.Close();
有声音,有按钮的提示对话框
//MessageBox.Show("读取成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
![具体样式](https://img-blog.csdnimg.cn/20210201201652359.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21seGc5OTk5OQ==,size_16,color_FFFFFF,t_70#pic_center)