用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打开是这样的:
到底怎么回事?
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架