一直以为这样可以关闭 fs, 其实不行

static void Main(string[] args)
                {
                                FileStream fs = null;
                                try
                                {
                                        fs = new FileStream(@"d:\data.txt", FileMode.Create);
                                        byte[] bytes = new UTF8Encoding().GetBytes("try");
                                        fs.Write(bytes, 0, bytes.Length);
                                        throw new Exception();//异常不作处理
                                }finally
                                {
                                        byte[] bytes = new UTF8Encoding().GetBytes(" finally");
                                        fs.Write(bytes, 0, bytes.Length);
                                        if (fs != null)
                                                fs.Close();
                                }
                }
  
要这样才能有效关闭 fs:
static void Main(string[] args) { try { FileStream fs = null; try { fs = new FileStream(@"d:\data.txt", FileMode.Create); byte[] bytes = new UTF8Encoding().GetBytes("try"); fs.Write(bytes, 0, bytes.Length); throw new Exception();//异常不作处理 }finally { byte[] bytes = new UTF8Encoding().GetBytes(" finally"); fs.Write(bytes, 0, bytes.Length); if (fs != null) fs.Close(); } } catch { throw; } }

 

相关文章:

  • 2022-12-23
  • 2021-09-23
  • 2021-10-27
  • 2021-09-12
  • 2022-01-31
猜你喜欢
  • 2022-01-18
  • 2021-10-20
  • 2021-07-14
  • 2021-12-04
  • 2022-01-31
  • 2021-10-19
相关资源
相似解决方案