文件管理
(1)用Directory类提供的方法确定指定的目录是否存在。如果不存在,则创建
目录然后在其中创建一个文件,并将一个字符串写入文件
(2)使用File类实现删除指定目录下的文件
(3)使用StreamReader和StreamWriter完成文本文件的读写
using System
;
using System
.Collections
.Generic
;
using System
.ComponentModel
;
using System
.Data
;
using System
.Drawing
;
using System
.Linq
;
using System
.Text
;
using System
.Threading
.Tasks
;
using System
.Windows
.Forms
;
using System
.IO;
namespace WindowsFormsApp1501
{
public partial
class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender
, EventArgs e
)
{
}
private void textBox1_TextChanged(object sender
, EventArgs e
)
{
}
private void button1_Click(object sender
, EventArgs e
)
{
string path1
= textBox1
.Text
;
if (Directory
.Exists(@textBox1
.Text
))
{
MessageBox
.Show("该路径存在现有目录");
}
else
{
DialogResult dr
= MessageBox
.Show("该路径不存在现有目录,是否创建","判断", MessageBoxButtons
.OKCancel
);
if(dr
== DialogResult
.OK)
{
if(@textBox1
.Text
== null)
{
MessageBox
.Show("路径出错");
}
else
{
try
{
Directory
.CreateDirectory(@path1
);
}
catch
{
MessageBox
.Show("路径出错");
}
}
}
else
{
}
}
}
private void label2_Click(object sender
, EventArgs e
)
{
}
private void textBox2_TextChanged(object sender
, EventArgs e
)
{
}
private void button2_Click(object sender
, EventArgs e
)
{
if(File
.Exists(@textBox1
.Text
))
{
MessageBox
.Show("路径已存在文件,无须创建", "创建");
}
else
{
try
{
File
.Create(@textBox1
.Text
).Close();
MessageBox
.Show("创建成功", "创建");
}
catch
{
MessageBox
.Show("路径出错");
}
}
}
private void Form1_Load(object sender
, EventArgs e
)
{
}
private void button3_Click(object sender
, EventArgs e
)
{
try
{
File
.AppendAllText(@textBox1
.Text
, textBox2
.Text
.ToString(),Encoding
.Default
);
MessageBox
.Show("插入成功");
}
catch
{
MessageBox
.Show("路径出错或未填写输入字符");
}
}
private void button4_Click(object sender
, EventArgs e
)
{
try
{
if (File
.Exists(@textBox1
.Text
))
{
File
.Delete(@textBox1
.Text
);
MessageBox
.Show("删除成功");
}
}
catch
{
MessageBox
.Show("文件不存在");
}
}
private void button5_Click(object sender
, EventArgs e
)
{
try
{
using (StreamReader sr
= new StreamReader(textBox1
.Text
))
{
String line
;
while((line
= sr
.ReadLine())!=null)
{
MessageBox
.Show(line
);
}
if((line
= sr
.ReadLine())== null)
{
MessageBox
.Show("为空");
}
}
}
catch
{
MessageBox
.Show("文件不存在或该文件不可读");
}
}
private void button6_Click(object sender
, EventArgs e
)
{
try
{
using (StreamWriter sw
= new StreamWriter(textBox1
.Text
))
{
sw
.WriteLine(textBox2
.Text
);
MessageBox
.Show("写入成功");
}
}
catch
{
MessageBox
.Show("字符串不存在或该文件不可写");
}
}
}
}
特别注意: 仅供参考学习,转载请附上原文链接 分享学习心得,如有侵权,望联系本人处理 还在读大学的程序员,项目经验少,如有纰漏,感谢指正 需要源代码请联系本人 谢谢配合
如果这篇文章对您有帮助,小小的点个赞,算是给小学弟的鼓励吧!谢谢大佬!!/呱呱.jpg