[英]Searching for a file from VB.NET
给定文件名后,如何有效地在磁盘上搜索该文件?
(Visual Studio 2005,即.NET 2.0)
您的问题含糊,您未指定任何编程语言。 因此,您可以使用命令提示符来执行此操作:
dir /s /b d:\<filename>
或使用您所使用的任何语言在系统调用中使用以上内容。
在C / C ++或使用本机Win32 API的任何其他语言中,使用:
并递归遍历您遇到的任何目录。 在C#/ VB /其他.Net语言中,它是:
如果您想实现搜索机制,我将从类似这样的内容开始(C#)
using System;
using System.Collections.Generic;
using System.IO;
namespace Samples.FileSearcher
{
public delegate void FileFoundHandler(string fileName);
public delegate void SearchStatChangeHandler( bool newStat);
public class FileSearch
{
private bool _isSearching;
private FileFoundHandler _fileFound;
private SearchStatChangeHandler _searchStatusChanged;
public bool IsSearching { get { return _isSearching; } }
public event FileFoundHandler FileFound{add { _fileFound += value; }remove { _fileFound -= value; }}
public event SearchStatChangeHandler SearchingStatusChanged { add { _searchStatusChanged += value; } remove { _searchStatusChanged -= value; } }
public void Search(string rootFolder, string filePattern)
{
ChangeStat(true);
Queue<string> folderList = new Queue<string>();
folderList.Enqueue(rootFolder);
while (folderList.Count > 0)
{
string currentFolder = folderList.Dequeue();
foreach (string folder in Directory.GetDirectories(currentFolder))
folderList.Enqueue(folder);
foreach (string foundFile in Directory.GetFiles(currentFolder, filePattern))
if (_fileFound != null)
_fileFound(foundFile);
}
ChangeStat(false);
}
private void ChangeStat(bool newStat)
{
_isSearching = newStat;
if (_searchStatusChanged != null) _searchStatusChanged(_isSearching);
}
}
}
这只是一个快速入门。 您应该使用它来实现表单,对Search Method进行一些错误处理,并可能需要取消标志,以便当您找到所需的内容时就不会永远搜索。
我用以下形式实现了我的表格:
private void button1_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
Samples.FileSearcher.FileSearch searcher = new Samples.FileSearcher.FileSearch();
searcher.FileFound += new FileFoundHandler(searcher_FileFound);
searcher.Search(textBox1.Text, textBox2.Text);
}
void searcher_FileFound(string fileName)
{
listView1.Items.Add(fileName);
}
如果您有更具体的疑问,请发布它们,我们将尝试调查并尽最大努力为您提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.