我正在用C#编写一个小程序来扫描文件夹并打开在程序上按下按钮后下午5点30分之后创建的文件。这也必须在子文件夹中搜索。
我需要一些解决方案来指出正确的方向,因为我不确定如何做到这一点。
这是文件夹观察程序的一部分。问题是当用户回家时,PC被关闭,并且在17.30之后有文件被创建到目录。所以我需要一种方法,当程序在早上重新启动时检测到17.30之后创建的任何内容并打开它们。
private void button1_Click(object sender, EventArgs e)
{
folderBrowser.ShowDialog();
textBox1.Text = folderBrowser.SelectedPath;
filewatcher.Path = textBox1.Text;
Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\COMPANY\\FOLDERWATCHER", "FOLDERPATH", textBox1.Text);
}
private void Form1_Load(object sender, EventArgs e)
{
String WatchFolder = Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\COMPANY\\FOLDERWATCHER", "FOLDERPATH", "").ToString();
textBox1.Text = WatchFolder;
filewatcher.Path = WatchFolder;
}
private void Form1_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
ShowInTaskbar = true;
Hide();
}
}
private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
{
if(!e.FullPath.EndsWith("temp.temp"))
{
MessageBox.Show("You have a Collection Form: " + e.Name);
Process.Start("explorer.exe", e.FullPath);
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
Show();
}
}
这是我上面的完整代码。我想使用一个按钮打开或显示17.30之后创建的文件。
答案 0 :(得分:19)
查看 System.IO 命名空间,它拥有您需要的一切。
DirectoryInfo 和文件类可以执行您想要的操作。
答案 1 :(得分:5)
以下是您要查找的递归方法:
public static List<string> GetFilesCreatedAfter(string directoryName, DateTime dt)
{
var directory = new DirectoryInfo(directoryName);
if (!directory.Exists)
throw new InvalidOperationException("Directory does not exist : " + directoryName);
var files = new List<string>();
files.AddRange(directory.GetFiles().Where(n => n.CreationTime > dt).Select(n=>n.FullName));
foreach (var subDirectory in Directory.GetDirectories(directoryName))
{
files.AddRange(GetFilesCreatedAfter(subDirectory,dt));
}
return files;
}
希望我帮助过。
答案 2 :(得分:3)
您可以使用FileSystemWatcher
(MSDN documentation)来检测按下按钮后创建的文件(在应用程序运行时)。
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "C:\\YourDirectory";
watcher.Created += (sender, args) => {
// File was created
}
watcher.EnableRaisingEvents = true;
这使您可以在创建文件时(在应用程序运行时)跟踪文件。
如果您只想获取在指定时间范围内(在应用程序启动之前)创建的所有目录的列表,则可以使用Directory.GetDirectories
和Directory.GetFiles
搜索目录树。
答案 3 :(得分:1)
代替日期时间,将日期和时间值放在一起。
void DirSearch(string dir)
{
try
{
foreach (string d in Directory.GetDirectories(dir))
{
foreach (string f in Directory.GetFiles(d, "*.*"))
{
if(DateTime.Compare(f.GetCreationTime, datetime))
{
//files found
}
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}