该进程无法访问该文件,因为该文件是由vb.net中的另一个进程创建的

时间:2018-09-17 15:45:38

标签: directory copy sleep filesystemwatcher

我正在使用FilesystemWatcher在目录中查找newfile。 调查的文件类型为 .blf 。正在创建的文件大小几乎为 10MB (不是恒定的,而是大约/几乎是数字) 创建文件并完全写入文件后,我要将文件复制到其他文件夹中。 但是,即使正在写入文件,该程序也会立即开始复制,并且出现以下错误: “该进程无法访问该文件,因为它是由另一个进程创建的” 我想做一个条件来检查文件是否已完全创建,然后进行复制; 下面是我的代码:

Private Sub Fsw1_Created(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Fsw1.Created
    ListBox2.Items.Add("File- " & e.FullPath.ToString & " created at: " & System.DateTime.Now)
    Dim blffolder As String = String.Format("C:\Users\nha4abt\Desktop\Main\blf_files" + "\{0}", DateTime.Today.ToString("dd-MMM-yyyy"))
    'Check if subfolders exists or not
    If (Not System.IO.Directory.Exists(blffolder)) Then
        System.IO.Directory.CreateDirectory(blffolder)
    End If
    'Repeat steps 1-6
    Dim destPath As String = Path.Combine(blffolder, Path.GetFileName(e.FullPath))
    'System.Threading.Thread.Sleep(1000)
    File.Copy(e.FullPath, destPath, True) 'copy all the files in destination folder 
    ' Compare the two files that are referenced in the textbox controls.
    If (FileCompare(e.FullPath, destPath)) Then
        ListBox1.Items.Add(e.FullPath & "-  is correctly copied :) ") ' put all the names in listbox; Not necessary
        'To Add: make a log file .txt to put the record of all the files that are copied during the process
        Dim strFile As String = String.Format(DestinationDirectory + "\Log_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy")) 'create a .txt file for log
        Dim texttoappend As String
        Dim timedate As String
        timedate = DateTime.Now
        texttoappend = e.FullPath + vbCrLf + "copied to" & vbCrLf & destPath & vbCrLf & "at" & timedate + vbNewLine & vbCrLf
        File.AppendAllText(strFile, String.Format(texttoappend, Environment.NewLine))
    Else
        MessageBox.Show("Files are not equal.")
        File.Copy(e.FullPath, destPath, True) 'copy again 
    End If

End Sub

我尝试使用 System.Threading.Thread.Sleep(1000),但无法运行该程序。请指导

1 个答案:

答案 0 :(得分:0)

我建议实现一个Function来检查文件是否仍在被另一个进程使用,并避免使用System.Threading.Thread.Sleep(1000)

Original function here

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
    if (stream != null)
        stream.Close();
    }

    //file is not locked
    return false;
}