winform中判断文件夹以及文件是否存在,文件夹不存在进行创建,文件存在进行删除

来源:互联网 发布:淘宝售假申诉能成功吗 编辑:程序博客网 时间:2024/05/18 17:43

1:文件夹是否存在,不存在进行创建

         //给一个默认的文件路径E:\\TestFolderIsExist
            string folderPath = this.txtfolder.Text;
            //文件夹不存在
            try
            {
                //这和asp.net的写法有点不一样
                if (System.IO.Directory.Exists(folderPath) == false)
                {
                    System.IO.Directory.CreateDirectory(folderPath);
                }
                MessageBox.Show("创建成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("创建失败");
                throw ex;
            }


2:判断文件是否存在,如果存在就删除

string filePath = “E:\\TestFileIsExist\\abc.txt”;

 if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                    MessageBox.Show("文件已经删除");
                }
                else
                {
                    MessageBox.Show("文件不存在");    

                   //接下来 可以进行保存文件的操作了
                }