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

问题描述 投票:1回答:1

我正在使用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)但无法运行该程序。请指导

directory copy sleep filesystemwatcher
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.