using([オブジェクトの宣言、オブジェクトのインスタンス化のコード])
{
...(処理)
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace SimpleUsingBlock
{
public partial class FormFileStream : Form
{
public FormFileStream()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (StreamWriter sw = new StreamWriter("test.txt", false, Encoding.GetEncoding("Shift-JIS"))) {
sw.Write("テストの書き込み");
textBox1.Text += "ファイルに書き込みました。\r\n";
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
using (StreamWriter sw = new StreamWriter("test.txt", false, Encoding.GetEncoding("Shift-JIS"))) {
sw.Write("テストの書き込み");
textBox1.Text += "ファイルに書き込みました。\r\n";
}
}
上記のusing 部分のコードは下記のコードと同様の動作に置き換えられます。private void button1_Click(object sender, EventArgs e)
{
{
StreamWriter sw = new StreamWriter("test.txt", false, Encoding.GetEncoding("Shift-JIS"));
try
{
sw.Write("テストの書き込み");
}
finally
{
if (sw != null) ((IDisposable)sw).Dispose();
}
}
}