C# 操作文件和文件夹

本文介绍了如何使用C#进行文件和目录的选择、获取文件信息以及文件的删除操作。具体包括使用OpenFileDialog选择Excel文件、FolderBrowserDialog选择目录、获取所选文件的路径、名称和类型等信息,并演示了如何删除文件或目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 选择文件
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "excel (*.xlsx)|*.xlsx|excel 2003 (*.xls)|*.xls"; //过滤文件类型
fd.Multiselect = true;//文件多选
fd.InitialDirectory = System.Windows.Forms.Application.StartupPath + "\\Temp\\";//设定初始目录,不设置就显示上次打开目录
fd.ShowReadOnly = false; //设定文件是否只读
DialogResult r = fd.ShowDialog();
if (r == DialogResult.OK)
{
    string filepath = fd.FileName;//文件完整路径
    string strPath = System.IO.Path.GetDirectoryName(filepath );//文件路径
    string fileName = System.IO.Path.GetFileName(filepath ); //文件名
    string fileType = System.IO.Path.GetExtension(filepath );//扩展名
}

2.选择目录     

System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
folderBrowserDialog1.Description = "选择文件所在文件夹";
folderBrowserDialog1.SelectedPath = "";//默认路径
if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    strPath = folderBrowserDialog1.SelectedPath;//
}
else
    return;

//获得目录下文件完整路径
String[] files1 = Directory.GetFiles(strPath, "*.txt", SearchOption.AllDirectories);//参数1:目录;参数2:文件类型;参数3:是否包含子级目录文件

3.   删除文件

//string fileName = ""//文件路径
//File.Delete(fileName);//文件删除
//Directory.Delete(path,true);//删除路径和路径下文件
string path = "";//路径
FileAttributes attr = File.GetAttributes(path);//路径属性
//判断path是文件还是文件夹路径
if (attr == FileAttributes.Directory)
{
    Directory.Delete(path,true);//删除路径和路径下文件
    //DirectoryInfo dir = new DirectoryInfo(path);
    //foreach (System.IO.FileInfo file in dir.GetFiles()) file.Delete();//删除当前路径路径下文件,不包括子目录。可以设置GetFiles(".txt",SearchOption.AllDirectories)的参数实现删除的文件类型及是否同时删除子目录文件
    //foreach (System.IO.DirectoryInfo subDirectory in dir.GetDirectories())        subDirectory.Delete(true);//删除子目录和子目录文件
}
else
{
    File.Delete(path);
}

4.创建文件

//新建文件夹
//string folderPath="文件夹位置"; 
//if (!Directory.Exists(folderPath))
     //Directory.CreateDirectory(folderPath);  

//复制模板以创建新文件
SaveFileDialog fd = new SaveFileDialog();
  fd.Filter = "Excel(*.xls)|*.xls"; //过滤文件类型 修改为要创建的文件类型
  fd.InitialDirectory = System.Windows.Forms.Application.StartupPath + "\\Temp\\";//设定初始目录
  DialogResult r = fd.ShowDialog();
  if (r == DialogResult.OK)
  {
      File.Copy( "~\\模板位置.xls", fd.FileName);
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值