我有以下情况,我必须复制多个(大约10,50,200,...)文件。我一个接一个地同步。这是我的代码片段。在线程中复制多个文件
static void Main(string[] args)
{
string path = @"";
FileSystemWatcher listener = new FileSystemWatcher(path);
listener.Created += new FileSystemEventHandler(listener_Created);
listener.EnableRaisingEvents = true;
while (Console.ReadLine() != "exit") ;
}
public static void listener_Created(object sender, FileSystemEventArgs e)
{
while (!IsFileReady(e.FullPath)) ;
File.Copy(e.FullPath, @"D:\levani\FolderListenerTest\CopiedFilesFolder\" + e.Name);
}
所以当某个文件夹中创建的文件,它已经准备好使用我复制该文件一个又一个,但我要开始任何文件就可以使用了,一旦复制。所以我认为我应该使用线程。所以.. 如何实现并行复制?
@克里斯
检查文件是否已准备
public static bool IsFileReady(String sFilename)
{
// If the file can be opened for exclusive access it means that the file
// is no longer locked by another process.
try
{
using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
{
if (inputStream.Length > 0)
{
return true;
}
else
{
return false;
}
}
}
catch (Exception)
{
return false;
}
}
也是一个警告的话......我相信创建的事件会在文件第一次创建时触发。如果文件需要一些时间来创建,你可能会发现你正在试图在它写完之前处理它... – Chris
@Chris在这里while(!IsFileReady(e.FullPath)); – levi
D'oh! :)你是如何检查出来的兴趣?我从来没有发现任何特别好的方法来检查它... – Chris