【问题标题】:Unable to read an open file with binary reader无法使用二进制阅读器读取打开的文件
【发布时间】:2012-01-03 11:26:44
【问题描述】:

我有这个功能来读取 SQL Server 错误日志,但问题是我无法读取服务器当时正在使用的错误日志。我一直在谷歌搜索,似乎 Fileshare 标志不适用于 powershell。当我尝试打开文件时,有什么方法可以设置 Fileshare 标志吗?

功能检查日志{ 参数($日志) $pos foreach($log in $logpos){ 如果($log.host -eq $logs.host){ $当前日志 = $日志 休息 } } if($currentLog -eq $null){ $currentLog = @{} $logpos.Add($currentLog) $currentLog.host = $logs.host $currentLog.event = $logs.type $currentLog.lastpos = 0 } $path = $logs.file if($currentLog.lastpos -ne $null){$pos = $currentLog.lastpos} 否则{$pos = 0} if($logs.enc -eq $null){$br = New-Object System.IO.BinaryReader([System.IO.File]::Open($path, [System.IO.FileMode]::Open)) } 别的{ $encoding = $logs.enc.toUpper().Replace('-','') if($encoding -eq 'UTF16'){$encoding = 'Unicode'} $br = 新对象 System.IO.BinaryReader([System.IO.File]::Open($path, [System.IO.FileMode]::Open), [System.Text.Encoding]::$encoding) } $required = $br.BaseStream.Length - $pos 如果($需要-lt 0){ $pos = 0 $required = $br.BaseStream.Length } if($required -eq 0){$br.close();返回 $null} $br.BaseStream.Seek($pos, [System.IO.SeekOrigin]::Begin)|Out-Null $bytes = $br.ReadBytes($required) $result = [System.Text.Encoding]::Unicode.GetString($bytes) $split = $result.Split("`n") foreach($s in $split) { if($s.contains("错误:")) { $errorLine = [正则表达式]::Split($s, "\s\s+") $err = [正则表达式]::Split($errorLine[1], "\s+") if(log_filter $currentLog.event $err[1..$err.length]){$Script:events = $events+ [string]$s + "`n" } } } $currentLog.lastpos = $br.BaseStream.Position $br.close() }

要明确的是,当我尝试打开文件时会出现错误。错误信息是:

 Exception calling "Open" with "2" argument(s): "The process cannot access the file
 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG' 
  because it is being used by another process."

吉斯利

【问题讨论】:

    标签: powershell file-io binaryreader


    【解决方案1】:

    所以我找到了答案,而且非常简单。

    二进制读取器构造函数将流作为输入。我没有单独定义流,这就是为什么我没有注意到您在流的构造函数中设置了 FileShare 标志。

    我要做的就是改变这个:

    {$br = New-Object System.IO.BinaryReader([System.IO.File]::Open($path, [System.IO.FileMode]::Open))}
    

    到这里:

    {$br = New-Object System.IO.BinaryReader([System.IO.File]::Open($path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite))}
    

    然后它就像一个魅力。

    吉斯利

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多