【问题标题】:Is there a method to determine if a System.IO.StreamWriter object is open?有没有一种方法可以确定 System.IO.StreamWriter 对象是否打开?
【发布时间】:2013-05-04 04:19:00
【问题描述】:

我正在尝试确定 StreamWriter 对象是否在脚本中打开或已关闭。如果它没有关闭,我可以在文件中写一个新行。如果它关闭了,我需要执行其他操作....

如何验证流是否仍然打开?

示例测试脚本。

$stream = [System.IO.StreamWriter] "C:\testing.txt"
$stream.WriteLine("TEST")
$stream.close()
if($stream)){
    #stream still open, write new line
    $stream.WriteLine("Stream is still open.  Write.")
    $stream.close()
}else(
    #stream not open... end script, send reponse.
}

【问题讨论】:

    标签: powershell file-io streamwriter


    【解决方案1】:

    您可以检查Streamwriter 对象是否存在BaseStream。像这样:

    if($stream.BaseStream)){
        #Stream is open
    }
    

    例子:

    $sw = New-Object System.IO.StreamWriter "C:\test.txt"
    
    PS > $sw | fl *
    
    
    AutoFlush      : False
    BaseStream     : System.IO.FileStream
    Encoding       : System.Text.UTF8Encoding
    FormatProvider : nb-NO
    NewLine        : 
    
    PS > if($sw.BaseStream) { "yes" }
    yes
    
    PS > $sw.Close()
    
    PS > if($sw.BaseStream) { "yes" }
    
    PS > $sw
    
    
    AutoFlush      : False
    BaseStream     : 
    Encoding       : 
    FormatProvider : nb-NO
    NewLine        : 
    

    编辑或者您可以检查以下之一:

    if($sw.BaseStream.CanWrite) {
        #You have permission to write = stream open and writeable
        }
    
    #or
    
    if($sw.BaseStream.SafeFileHandle) {
        #you have a filehandle = stream open
        }
    

    【讨论】:

    • 如果你直接关闭底层流,这是行不通的。 (我没有注意到 stream 实际上是一个 StreamWriter)
    • 好吧,但你为什么要保护自己免受这种伤害呢?他控制他的代码。他正在使用streamwriter。只要他像普通人一样使用$stream.Close() 而不是$stream.basestream.close(),他应该没问题,对吧?我已经更新了一些其他的东西,他可以检查一下,如果他以某种方式关闭了basestream
    猜你喜欢
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多