【问题标题】:Closing and releasing the file after use使用后关闭并释放文件
【发布时间】:2022-11-21 05:10:27
【问题描述】:
 try
 {
      using (MemoryStream stream = new MemoryStream())
      {
                path = Server.MapPath(@"\\Files\\" + "file.txt");
                StreamWriter tw = new StreamWriter(path, false, Encoding.GetEncoding("windows-1255"));
                tw.Write("Hello dear file");
               
                tw.Flush();
                tw.Close();
                tw.Dispose();

                stream.Close();
                stream.Dispose();  
            }
        }
        catch (Exception  ex)
        {
            string msg = ex.Message;// Error
            return null;
        }
        return path;

再次使用时报错:

该进程无法访问该文件,因为另一个进程正在使用该文件

如何释放文件的使用以启用重用?

【问题讨论】:

  • 确认是否释放锁,手动重命名文件,如果文件仍然被锁定,你会得到一个错误
  • 您应该为 StreamWriter 使用 using 语句,就像您为 MemoryStream 一样。您应该对在有限范围内使用的所有一次性对象执行此操作。
  • @jmcilhinney 好的,我做到了!它没有帮助我。

标签: c# asp.net file server.mappath


【解决方案1】:

您需要在处理文件的任何地方使用此模式:

    using (_httpClient = new HttpClient())
{
//code to do
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2012-09-08
    相关资源
    最近更新 更多