如何在PowerShell中配置System.Xml.XmlWriter

时间:2009-04-14 00:57:55

标签: powershell dispose idisposable

我正在尝试处理XmlWriter对象:

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

错误:

  

方法调用失败,因为   [System.Xml.XmlWellFormedWriter]   不包含名为的方法   '处置'。

另一方面:

 $writer -is [IDisposable]
 # True

我该怎么办?

2 个答案:

答案 0 :(得分:11)

System.Xml.XmlWriter上处理protected。您应该使用Close代替。

$writer.Close

答案 1 :(得分:8)

这是另一种方法:

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

可以在http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx找到Get-Interface脚本,并在此response中提出建议。

使用'using'关键字,我们得到:

$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')) {

}
相关问题