0

我正在尝试编写一个简单的文本文件编写器。

如果我在使用 writer 时抛出异常,它会自动关闭吗?

可以这样写吗,因为它可以工作并且只有三行。如果文件不存在,则添加它并将文本写入其中;如果它确实存在,那么它会附加文本吗?

我在网上找到的所有其他示例都太长太复杂了?

Try
    For index = 1 To 100 Step 1

        Dim filePath As String = "c:\TextFile2.txt"

        Using writer As New StreamWriter(filePath, True)
            writer.WriteLine("Important data line" & index)

            ''Throw New ArgumentException("Exception Occured")

        End Using
    Next

Catch ex As Exception

    Console.WriteLine(ex.Message)
    Console.ReadLine()
End Try
4

1 回答 1

2

"using" is essentially a wrapping for a try/finally and dispose will be called as expected.

EXAMPLE:

WebClient c=new WebClient();
c.Disposed+= (sender, args) => {Console.WriteLine("DISPOSED");};
    using(c){
    throw new Exception("testing dispose");
    }
于 2012-11-04T18:22:35.077 回答