Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dispose System.Xml.XmlWriter in PowerShell

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?

like image 300
alex2k8 Avatar asked Apr 14 '09 00:04

alex2k8


2 Answers

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

$writer.Close
like image 76
Michael Avatar answered Oct 06 '22 14:10

Michael


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

}
like image 21
alex2k8 Avatar answered Oct 06 '22 12:10

alex2k8