用try...catch语句的代码:
结果成功的创建了一个Temp.dat文件,并且写入了数据。
问题:
打开Temp.dat文件,发现内容是这样的:
1. 用EditPlus打开是这样的:

2. 用记事本打开是这样的:

3. 用word打开是这样的:

到底怎么回事?
//创建要写入临时文件的字节
Byte[] bytesToWrite = new Byte[]{ 1 , 2, 3, 4, 5 };
//创建临时文件
FileStream fs = null;
try
{
fs = new FileStream( @"d:\Temp.dat" , FileMode.Create );
//将字节写入临时文件
fs.Write( bytesToWrite , 0 , bytesToWrite.Length );
}
finally
{
//在写入字节后显式关闭文件
if( fs != null )
{
//FileStream类虽然实现了IDisposable接口的Dispose方法,
//但是却是protected类型的方法,不能被其他类调用
//所以要用下面这样的语句来释放资源
((IDisposable)fs).Dispose();
}
}
Byte[] bytesToWrite = new Byte[]{ 1 , 2, 3, 4, 5 };
//创建临时文件
FileStream fs = null;
try
{
fs = new FileStream( @"d:\Temp.dat" , FileMode.Create );
//将字节写入临时文件
fs.Write( bytesToWrite , 0 , bytesToWrite.Length );
}
finally
{
//在写入字节后显式关闭文件
if( fs != null )
{
//FileStream类虽然实现了IDisposable接口的Dispose方法,
//但是却是protected类型的方法,不能被其他类调用
//所以要用下面这样的语句来释放资源
((IDisposable)fs).Dispose();
}
}
用using语句的代码,效果一样,代码简介很多:
//创建要写入临时文件的字节
Byte[] bytesToWrite = new Byte[]{ 1, 2, 3, 4, 5 };
//创建临时文件
using( FileStream fs = new FileStream( @"D:\Temp.dat" , FileMode.Create ) )
{
//将字节写入临时文件
fs.Write( bytesToWrite , 0 , bytesToWrite.Length );
}
Byte[] bytesToWrite = new Byte[]{ 1, 2, 3, 4, 5 };
//创建临时文件
using( FileStream fs = new FileStream( @"D:\Temp.dat" , FileMode.Create ) )
{
//将字节写入临时文件
fs.Write( bytesToWrite , 0 , bytesToWrite.Length );
}
结果成功的创建了一个Temp.dat文件,并且写入了数据。
问题:
打开Temp.dat文件,发现内容是这样的:
1. 用EditPlus打开是这样的:
2. 用记事本打开是这样的:
3. 用word打开是这样的:
到底怎么回事?
浙公网安备 33010602011771号