更新时间:2023-11-22 22:45:28
下面是使用使用
块,这将关闭该文件为你读文件的示例
Below is an example of reading a file using a using
block, which will close the file for you:
using (FileStream fs = File.OpenRead(@"c:\path\filename.txt")) //Open the file here
{
using (StreamReader sr = new StreamReader(fs))
{
while (!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
}
} //File will close when scope of this brace ends.
有些人preFER省略括号外的水平时,有连续的使用
块。我已经包括了他们的清晰度。请注意,使用
块使用尝试,终于
在幕后块,以确保您的文件将关闭,即使有是未捕获的异常。这是一件好事。
Some people prefer to omit the outer level of the braces when there are consecutive using
blocks. I have included them for clarity. Note that a using
block uses a try-finally
block under the covers to ensure that your file will close even if there is an uncaught exception. This is a good thing.
参见 RAII 。