我试图确定一个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.
}
答案 0 :(得分:5)
您可以检查BaseStream
- 对象是否存在Streamwriter
。像这样:
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
}