Процесс не может получить доступ к файлу, потому что он создается другим процессом в vb.net - PullRequest
0 голосов
/ 17 сентября 2018

Я использую FilesystemWatcher для поиска нового файла в каталоге. Тип исследования - .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 голосов
/ 25 марта 2019

Я бы предложил реализовать Function, который проверяет, используется ли файл другим процессом, и избегать System.Threading.Thread.Sleep(1000).

Оригинальная функция здесь

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;
}
...