次のシナリオがあります。複数(約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;
}
}