我有以下情况,我必须复制多个(大约 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;
}
}
最佳答案
从机械磁盘执行并行 I/O 是一个坏主意,只会减慢速度,因为机械磁头每次都需要旋转以寻找下一个读取位置(一个非常缓慢的过程),然后会被反弹轮到每个线程运行时。
坚持顺序方法并在单个线程中读取文件。
关于c# - 在线程中复制多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11029043/