C#工人:在每个循环通行证中读取并执行一个一个文件
在我的目录中,有几个(.sql-)文件。现在,我正在尝试编写一个Worker Service,该服务抓取一个文件,执行该文件并之后将其删除。然后,他将前进到下一个,依此类推,直到没有文件再也没有文件为止。
我已经编写了一些代码:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
string[] filePaths = Directory.GetFiles(@"E:\MyFolder\");
if (filePaths.Length != 0)
{
foreach (string filePath in filePaths)
{
ExecuteSQLFile(filePath);
}
}
await Task.Delay(1000, stoppingToken);
}
}
正如您希望可以看到的,使用命令directory.getfiles(@“ e:\ myFolder \”)
他总是在while -loop。
我现在尝试实现的是,在每个循环通行证中,他只读取一个文件并执行该文件,在下一个循环中通过下一个文件,依此类推。
有可能吗?有人可以协助并向我展示如何做到这一点吗?还是您至少可以给我一个小提示?如何在上面的代码中摆脱foreach
-loop?
in a directory of mine, there are several (.sql-)files. Now I am trying to write a worker service, which grabs one file, executes it and deletes it afterwards. Then he shall go forward to the next one and so on, until no file is there anymore.
I already wrote some code:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
string[] filePaths = Directory.GetFiles(@"E:\MyFolder\");
if (filePaths.Length != 0)
{
foreach (string filePath in filePaths)
{
ExecuteSQLFile(filePath);
}
}
await Task.Delay(1000, stoppingToken);
}
}
As you hopefully can see, with the command Directory.GetFiles(@"E:\MyFolder\")
he always reads the complete file system in each loop pass of the while
-loop.
What i try to achieve now, is that in each loop pass, he only reads ONE file and executes it, in the next loop pass the next one and so on.
Is that possible? Can someone please assist and show me how to do this? Or can you at least give me a small hint? How to get rid of the foreach
-loop in the code above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

OP(再次)更改了问题的前提。现在,我们只需要处理新文件,执行的文件将被删除。这使得
删除文件安全的工作要容易得多,而不是
file.delete
,删除文件可能会失败的方式多大,谢谢href =“ https://stackoverflow.com/users/18307736/gabriel”> gabriel 指出
directory.enumeratefiles
存在,让我只能阅读我感兴趣的文件在,并且不每次都读取目录的全部内容OP (once again) changed the premise of the question. Now we only have to deal with new files, the ones executed are deleted. That makes this quite a bit easier
Note that deleting a file safely is somewhat more work than just
File.Delete
, there are tons of ways deleting a file could failThanks Gabriel for pointing out that
Directory.EnumerateFiles
exists, allowing me to read just the files I'm interested in, and not read out the entire content of the directory every time