这两天做一个外部接口的应用程序,因为对方提供的数据全部来自于一个txt文档,并且要在指定的文件夹下操作,因此用到了文件目录的查找和搜索:
我的文件的具体路径默认为C:/jdda/marpup/response.txt,因此在不缺省的情况下就必须自己动手查找文件目录jdda/marpup了!
下面是具体的方法,递归用法是一定了:
private string strDirectory = string.Empty; //声明变量存储具体路径
/// <summary>
/// 查找安装目录
/// </summary>
/// <param name="directorypath">要查找的目录</param>
/// <returns></returns>
private void GetDirectory(string directorypath)
{
DirectoryInfo info = new DirectoryInfo(directorypath);
// 这里的两个参数,
// 第一个是搜索字符串,像windows搜索一样,可以用通配符如 'mar*'
// 第二个是搜索范围枚举,当前目录还是所有子目录
foreach (DirectoryInfo dir in info.GetDirectories("marpup", SearchOption.AllDirectories))
{
if (dir != null)
{
str = dir.FullName;
break;
}
GetDirectory(dir.FullName);
}
}
具体调用:
private void button1_Click(object sender, EventArgs e)
{
GetDirectory("c://");
MessageBox.Show("具体路径为"+str);
}
对文件的具体操作,这里我不说了,把DirecotryInfo改为FileInfo后使用,具体要更改
注意:这里可能会出现错误:“System Volume Information”拒绝访问
解决办法:
设置关闭系统还原,节省磁盘空间:
1、打开我的电脑属性 ;
2、选择系统还原选项卡 ;
3、将“在所有驱动器上关闭系统还原”打勾确定;
4、关闭“系统还原”后,删除该驱动器根目录下的“System Volume Information”文件夹。