VB.Net 3.5检查文件是否正在使用 [英] VB.Net 3.5 Check if file is in use
问题描述
我有一个完全独立于我的主应用程序的更新程序。我运行update.exe来更新app.exe。要检查文件是否正在使用中,我将其移至另一个文件并在使用中捕获错误。如果没有问题,我将其重命名。至少那是我的计划...
I have an update program that is completely independent of my main application. I run the update.exe to update the app.exe. To check to see if the file is in use, I move it to another file and catch an error if it is in use. If no problems occurr I rename it back. At least that was my plan...
主程序:app.exe
更新程序:更新。 exe
Main program: app.exe
Update program: update.exe
该程序在网络上使用,没有任何服务在运行。因此,用户实际上是在他们的计算机上通过网络运行exe。
This program is used over the network without any services running. So, the users is quite literally running the exe over the network on thier machine.
当update.exe运行时,我需要更新app.exe。要检查app.exe是否仍在使用中,我将以下内容包装在try / catch中,以查看是否失败:
I need to update the app.exe when the update.exe has run. To check to see if the app.exe was still in use I was wrapping the following in a try/catch to see if it failed:
IO.File.Move(upddir& \app.exe,upddir& \app.exe.tst)
IO.File.Move(upddir& \ \app.exe.tst,upddir和 \app.exe)
IO.File.Move(upddir & "\app.exe", upddir & "\app.exe.tst")
IO.File.Move(upddir & "\app.exe.tst", upddir & "\app.exe")
有趣的是,即使app.exe正在运行,移动可以将其重命名为app.exe.tst,而不会发生任何错误。我什至可以继续进行应用程序而不会出现任何错误。
The funny thing is, even if the app.exe is running, the move can rename it to the app.exe.tst without any error. I can even continue on in the application without any errors.
我以为我不介意,所以我让另一个程序员看了一下,他证实了我上面说的话。
I thought I was out of my mind, so I had another programmer look at this and he verified what I said above.
因此,我们尝试将其包装在try catch中:
So, we tried this wrapped in a try catch:
将readfile设置为New FileStream(upddir& \ app.exe,FileMode.Open,FileAccess.Read,FileShare.None)。
readfile.Dispose()
Dim readfile As New FileStream(upddir & "\app.exe", FileMode.Open, FileAccess.Read, FileShare.None)
readfile.Dispose()
我把文件共享设置为否,至少我认为这表明文件中有人。
I put the fileshare as none that, at least I thought it would, show that there was someone in the file.
它仍然继续运行,没有任何错误。
It still continued without any error.
谁知道为什么我可以重命名正在使用的文件?
另外,有没有比我现在做的更好的方法了?
Anyone know why I can rename a file in use? Also, is there a better way to do this than what I am doing now?
谢谢!
Eroc
Thanks! Eroc
推荐答案
您可以执行以下操作来检查应用程序是否正在运行其他实例:
You could do the following to check if the application has other instances running:
Process.GetProcessesByName("app.exe", "Machine1").Length > 0
检查应用程序是否运行的更合适的方法。
Which is a more appropriate way of checking if the app is running.
看看 File.Move MSDN文档。它详细说明了抛出什么异常。即使在Vista中使用了exe,也可以重命名它。
Have a look at File.Move MSDN documentation. It details what exceptions are thrown. You are allowed to rename an exe even if it is in Use in Vista.
这篇关于VB.Net 3.5检查文件是否正在使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!