我正在尝试根据创建日期将csv文件从一个位置移动到另一个位置。
但我使用的代码没有显示错误,表示sample.csv已被其他进程使用,我该如何解决此问题?
这是错误消息“错误:System.Reflection.TargetInvocationException:调用目标已抛出异常.---> System.IO.IOException:进程无法访问文件'C:\ New folder \ Test.txt'因为它正由另一个进程使用。 在System.IO .__ Error.WinIOError(Int32 errorCode,String maybeFullPath) 在System.IO.File.InternalCopy(String sourceFileName,String destFileName,Boolean overwrite) 在ST_b8571e8d94a54a80ab50a1e221d93b11.vbproj.ScriptMain.Main() ---内部异常堆栈跟踪结束--- at System.RuntimeMethodHandle._InvokeMethodFast(Object target,Object [] arguments,SignatureStruct& sig,MethodAttributes methodAttributes,RuntimeTypeHandle typeOwner) at System.RuntimeMethodHandle.InvokeMethodFast(Object target,Object [] arguments,Signature sig,MethodAttributes methodAttributes,RuntimeTypeHandle typeOwner) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj,BindingFlags invokeAttr,Binder binder,Object [] parameters,CultureInfo culture,Boolean skipVisibilityChecks) 在System.Reflection.RuntimeMethodInfo.Invoke(Object obj,BindingFlags invokeAttr,Binder binder,Object []参数,CultureInfo文化) at System.RuntimeType.InvokeMember(String name,BindingFlags bindingFlags,Binder binder,Object target,Object [] providedArgs,ParameterModifier [] modifiers,CultureInfo culture,String [] namedParams) at System.Type.InvokeMember(String name,BindingFlags invokeAttr,Binder binder,Object target,Object [] args,CultureInfo culture) 在Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()“
Public Sub Main()
Dim csvFilesToday = New List(Of String)
Dim sourceDir As String = "C:\New folder"
Dim backupDir As String = "C:\New folder (2)"
For Each csv In Directory.GetFiles(sourceDir, "*.csv", IO.SearchOption.AllDirectories)
If File.GetCreationTime(csv).Date = Date.Today Then
File.Copy(Path.Combine(sourceDir, csv), Path.Combine(backupDir, csv), True)
End If
Next
Dts.TaskResult = ScriptResults.Success
End Sub
End Class
答案 0 :(得分:1)
您必须确定对文件进行锁定的进程。
我有一篇关于如何使用进程资源管理器来完成此任务的文章:File in use by another process
虽然快速但是如果打开它就关闭Excel。否则,请检查文本编辑器
答案 1 :(得分:0)
这不会解决您的问题,但会改善您的代码:
Public Sub Main()
Dim sourceDir As New DirectoryInfo("C:\New folder")
Dim backupDir As String = "C:\New folder (2)"
'Using DirectoryInfo.EnumerateFiles will reduce the total number of disk accesses
For Each csv In sourceDir.EnumerateFiles("*.csv", SearchOption.AllDirectories.Where(Function(i) i.CreationTime >= Date.Today)
Try
File.Copy(csv.FullName, Path.Combine(backupDir, csv.Name), True)
Catch Ex As IOException
'Do something with the error here
End Try
Next csv
Dts.TaskResult = ScriptResults.Success
End Sub