gpt4 book ai didi

c# - 等待将文件添加到目录的阻塞方法

转载 作者:太空宇宙 更新时间:2023-11-03 21:36:18 25 4
gpt4 key购买 nike

我想知道如何制作可以像那样工作的东西。从 Java 1.7 开始我可以使用 WatchService 但如何在 C# 中做到这一点?我想让这个方法阻塞,而不是通常的事件,所以它会永远等待直到出现新文件。

while(isANewFileInDirectory(path)){
doSomeCode();
}

编辑:

     FileSystemWatcher watcher = new FileSystemWatcher(".\\Screenshots");
watcher.Created += watcher_Created;

void watcher_Created(object sender, FileSystemEventArgs e) {
System.Diagnostics.Debug.WriteLine("fasuigfasuigf423432FSDFSAasuigf");
sendResponse(e.FullPath);
}

最佳答案

一定要阻塞吗?您可以使用文件观察器... http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx

编辑:这里是一个例子:

namespace FileWatchTest
{
class Program
{
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher(@"c:\temp");
watcher.EnableRaisingEvents = true;
watcher.Created += (obj, arg) => Console.WriteLine("File {0} created", arg.Name);
watcher.Deleted += (obj, arg) => Console.WriteLine("File {0} deleted", arg.Name);
watcher.Changed += (obj, arg) => Console.WriteLine("File {0} changed", arg.Name);

Console.ReadLine();
}
}
}

将其粘贴到控制台应用程序中,您应该会看到更新(显然 - 将路径更改为您要观看的文件夹...)

关于c# - 等待将文件添加到目录的阻塞方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21624074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com