EventArgs e){ // 判断文件名是否为空 if ( string .IsNullOrWhiteSpace(

时间:2021-09-30 06:58:45

1、创建和删除目录

  在c#中涉及到输入、输出(i/o)相关操纵的API都被放在System.IO定名空间下,,或者子命令System.IO.IsolatedStoorage中。对目录进行操纵可以使用Directory类和DirectoryInfo类。Directory类,供给了一些便捷的要领可以辅佐开发人员轻松的对目录进行操纵。DirectoryInfo类的成果和Directory类相似,果然了更多的成员以获得目录信息。

  使用两个按钮实现,文件目录的创建和删除

EventArgs e){ // 判断文件名是否为空 if ( string .IsNullOrWhiteSpace(

//引入输入、输出定名空间。 using System.IO; namespace WindowsFormsApp1 { public partial class Form1 : Form { //声明两个私有字段 DirectoryInfo dirInfo = null;//操纵目录的东西 string dirName = string.Empty;//用于存储目录名称 public Form1() { InitializeComponent(); } //创建按钮Click private void button1_Click(object sender, EventArgs e) { //判断输入是否为空 if(string .IsNullOrWhiteSpace(textBox1.Text)) { //打印提示语句 MessageBox.Show("IN err"); return; } dirName = textBox1.Text.Trim();//从当前System.String 东西移除所有空白字符和尾部空白字符 生存在目录名中 dirInfo = new DirectoryInfo(dirName);//实例dirInfo //判断目录是否存在 if(dirInfo.Exists)//如果目录存在,则为 true;否则为 false。 { dirInfo.Delete();//如果存在删除目录 } //创建目录 dirInfo.Create(); MessageBox.Show("目录" + dirName + "创建告成"); } private void Form1_Load(object sender, EventArgs e) { } //删除按钮Click private void button2_Click(object sender, EventArgs e) { if(dirInfo!=null && !string.IsNullOrWhiteSpace(dirName)) { dirInfo.Delete(); dirInfo = null; } } } }

注意:如果但愿在指定的目录下创建目录,可以指定绝对路径。

2、创建文件和删除文件

  与目录操纵相似,对付文件操纵,同样有两个类可以选择。File类和FileInfo类。

EventArgs e){ // 判断文件名是否为空 if ( string .IsNullOrWhiteSpace(

  

//引入文件定名空间 using System.IO; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string fileName = string.Empty;//用于存放新文件的名字 private void Form1_Load(object sender, EventArgs e) { } //Create Click Button function private void Create_Click(object sender, EventArgs e) { //判断文件名是否为空 if(string.IsNullOrWhiteSpace(Name.Text)) { MessageBox.Show("文件名为空"); return; } fileName = Name.Text; //如果文件已存在,删除 if (File.Exists(fileName))//确定指定文件是否存在 { File.Delete(fileName); } var fs = File.Create(fileName);//创建文件 //向文件写入3000字节 Random rand = new Random(); byte[] buf = new byte[3000]; rand.NextBytes(buf);//使用随机数填充指定字节数组元素 fs.Write(buf, 0, buf.Length);//将字节快写去文件流 MessageBox.Show("创建"+fileName+"告成"); fs.Dispose();//释放资源,Syst.IO.Stream使用的资源 } private void Delete_Click(object sender, EventArgs e) { if(File.Exists(fileName)) { File.Delete(fileName);//删除文件 } } } }