How can I dispose System.Xml.XmlWriter in PowerShell

隐身守侯 提交于 2019-12-30 04:27:11

问题


I am trying to dispose XmlWriter object:

try
{
    [System.Xml.XmlWriter] $writer = [System.Xml.XmlWriter]::Create('c:\some.xml')
}
finally
{
    $writer.Dispose()
}

Error:

Method invocation failed because [System.Xml.XmlWellFormedWriter] doesn't contain a method named 'Dispose'.

On the other side:

 $writer -is [IDisposable]
 # True

What should I do?


回答1:


Dispose is protected on System.Xml.XmlWriter. You should use Close instead.

$writer.Close



回答2:


Here is an alternative approach:

(get-interface $obj ([IDisposable])).Dispose()

Get-Interface script can be found here http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx and was suggested in this response.

With 'using' keyword we get:

$MY_DIR = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

# http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx
. ($MY_DIR + '\get-interface.ps1')

# A bit modified code from http://blogs.msdn.com/powershell/archive/2009/03/12/reserving-keywords.aspx
function using
{
    param($obj, [scriptblock]$sb)

    try {
        & $sb
    } finally {
        if ($obj -is [IDisposable]) {
            (get-interface $obj ([IDisposable])).Dispose()
        }
    }
}

# Demo
using($writer = [System.Xml.XmlWriter]::Create('c:\some.xml')) {

}


来源:https://stackoverflow.com/questions/745956/how-can-i-dispose-system-xml-xmlwriter-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!