我正在尝试读取局域网上远程PC上的Windows更新日志。大多数情况下,我可以成功读取文件,但有时程序锁定。可能由于某个问题或另一个问题 - 并不重要。我所需要的是一种在Filestream/Streamreader锁定时恢复的方法 - 我不确定是哪一个导致锁定。有些流可以设置超时,但下面的文件流在.CanTimeout调用上返回False。Filestream只读锁定PC
如何锁定流锁定? (有时锁是如此之紧以致需要关闭电源才能恢复。)
有没有一种方法可以在我实际尝试读取之前测试流是否会失败?
是否有另一种方法来读取另一个程序已打开的远程日志文件? (我使用的是流的方法,因为正规File.IO被阻止,因为该文件是在远程PC上打开)。
我越来越近了(我觉得)这个代码。我浏览了引用文章中的PathExists代码,但它是OP而不是答案。
Imports System.IO
Import System.Threading
...
Function GetAULog(PCName As String) As String
Try
Dim sLogPath As String = String.Format("\\{0}\c$\Windows\SoftwareDistribution\ReportingEvents.log", PCName)
If PCName = My.Computer.Name Then
sLogPath = String.Format("C:\Windows\SoftwareDistribution\ReportingEvents.log", PCName)
End If
' read file open by another process
If Not pathExists(sLogPath) Then
MsgBox("AU log file not found - PC on?")
Return "NA"
End If
Using fs As New FileStream(sLogPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Using sr As New StreamReader(fs)
Dim s As String = sr.ReadToEnd
Return s
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
Return ""
End Try
End Function
Public Function pathExists(path As String) As Boolean
Dim exists As Boolean = True
Dim t As New Thread(New ThreadStart(Sub() exists = System.IO.File.Exists(path)))
t.Start()
Dim completed As Boolean = t.Join(500)
'half a sec of timeout
If Not completed Then
exists = False
t.Abort()
End If
t = Nothing
Return exists
End Function
至少当PC关闭时pathExists()代码在短时间内返回False。
我现在的问题是程序退出时没有结束 - 至少在IDE中没有检查运行时。
我加了t = Nothing
但这没有帮助。我无法弄清楚正确的使用语法来测试。 线程超时后如何正确清理?
这可能不是我的问题,因为文件(如果存在的话)(我需要更改我的代码以检查Exists)是合理的大小。它似乎挂在连接时间。 Exists可能会暴露连接问题,并希望超时。 – rheitzman
当我遇到问题时,无论是大文件还是小文件都无所谓。我们正在使用脚本将.net应用程序推送到30个不同的机器。间歇性地,这些机器中的少数将会有文件共享锁定,直到重新启动完成。用上面提到的这种方法修复它。 – FloatingKiwi
我真的没有很好的机会访问目标机器,所以我需要更多的通用解决方案。 – rheitzman