directory - 进程无法访问该文件,因为它是由 vb.net 中的另一个进程创建的
问题描述
我正在使用 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)但无法运行该程序。请指导
解决方案
我建议实施一个Function
which 检查文件是否仍在被另一个进程使用并避免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;
}
推荐阅读
- azure - 如何设置 app.UseOAuthBearerAuthentication 来处理不同的 Azure B2C 自定义策略?
- e2e-testing - cy.getBy*** 不是函数
- python - plotfly 袖扣不会创建情节
- android - 单击输入元素会将已安装的 Web 应用程序从“独立”更改为“最小 UI”
- performance - 如何索引 cosmosDB 中的缺失值?
- google-apps-script - 如何创建一个在 K 列的第一个空单元格中写入日期的按钮
- excel - 有没有办法在多个 VBA 脚本中使用相同的代码?
- scala - 使用 spark databricks 平台从 URL 读取数据
- javascript - 为什么我的程序会中断?为什么我会收到此错误?
- c# - 如何处理多个值的 DBNull 异常