c#在本地驱动器上找到一个特定的文件



我想写一些代码来找到一个特定的文件(例如myfile.exe)我发现了各种代码片段,但当您扫描驱动器的根时,没有一个工作。例如

private string Findfile(string myname)
{
var files = new List<string>();
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
try
{
Updatestatus("Searching " + d.RootDirectory.FullName);
files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, myname, SearchOption.AllDirectories));
}
catch { }
}
if (files.Count == 0) { return "Not Found"; } else {
return files.First(); }
}

当我像上面那样尝试捕获任何错误时(例如,如果它试图扫描回收站,它会抛出一个错误),整个驱动器将被跳过。在堆栈交换的许多其他示例中,如果从驱动器的根级别开始并隐式扫描,则会抛出同样的问题。

GetFiles将在您获得异常时立即中止(通常是由于没有读权限)。最好的方法是像

下面的代码一样递归
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace SAveDirectoriesXml
{
class Program
{
const string FILENAME = @"c:temptest.xml";
const string FOLDER = @"c:temp";
static XmlWriter writer = null;
static void Main(string[] args)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
writer = XmlWriter.Create(FILENAME, settings);
writer.WriteStartDocument(true);
DirectoryInfo info = new DirectoryInfo(FOLDER);
WriteTree(info);

writer.WriteEndDocument();
writer.Flush();
writer.Close();
Console.WriteLine("Enter Return");
Console.ReadLine();
}
static long WriteTree(DirectoryInfo info)
{
long size = 0;
writer.WriteStartElement("Folder");
try
{
writer.WriteAttributeString("name", info.Name);
writer.WriteAttributeString("numberSubFolders", info.GetDirectories().Count().ToString());
writer.WriteAttributeString("numberFiles", info.GetFiles().Count().ToString());
writer.WriteAttributeString("date", info.LastWriteTime.ToString());

foreach (DirectoryInfo childInfo in info.GetDirectories())
{
size += WriteTree(childInfo);
}

}
catch (Exception ex)
{
string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
Console.WriteLine(errorMsg);
writer.WriteElementString("Error", errorMsg);
}
FileInfo[] fileInfo = null;
try
{
fileInfo = info.GetFiles();
}
catch (Exception ex)
{
string errorMsg = string.Format("Exception FileInfo : {0}, Error : {1}", info.FullName, ex.Message);
Console.WriteLine(errorMsg);
writer.WriteElementString("Error",errorMsg);
}
if (fileInfo != null)
{
foreach (FileInfo finfo in fileInfo)
{
try
{
writer.WriteStartElement("File");
writer.WriteAttributeString("name", finfo.Name);
writer.WriteAttributeString("size", finfo.Length.ToString());
writer.WriteAttributeString("date", info.LastWriteTime.ToString());
writer.WriteEndElement();
size += finfo.Length;
}
catch (Exception ex)
{
string errorMsg = string.Format("Exception File : {0}, Error : {1}", finfo.FullName, ex.Message);
Console.WriteLine(errorMsg);
writer.WriteElementString("Error", errorMsg);
}
}
}
writer.WriteElementString("size", size.ToString());
writer.WriteEndElement();
return size;
}
}
}

相关内容

  • 没有找到相关文章

最新更新