使用Using机制:
1.操作硬盘,就需要try...catch
2.为了简化try...catch的机制,使用Using
3.凡是使用了Using()自动释放资源的地方,必须实现IDisposable接口
源代码:
/***
* 使用Using自动释放资源,不用再写fs.Close()
*
*
*
*
*
*
*
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace 使用Using机制
{
class Program
{
private string _path = @"E:\任向飞\CSharp\c#进阶刘国柱\IO序列化\使用Using机制\bin\Debug\Test.txt";
public void Test3()
{
if (File.Exists(_path))
{
using (FileStream fs = new FileStream(_path, FileMode.Open))
{
//开辟内存区域,1024K空间=1M,如果数据量大可以定义的大一点比如10M
byte[] byteArray = new byte[1024 * 1024];
//开始读取数据
int count = fs.Read(byteArray, 0, byteArray.Length);
//byte数组转字符串
string str = Encoding.UTF8.GetString(byteArray, 0, count);
//关闭文件流,释放资源,释放内存
//fs.Close();
//显示数据
Console.WriteLine(str);
}
}
}
static void Main(string[] args)
{
Program obj = new Program();
obj.Test3();
Console.ReadKey();
}
}
}