Search code examples
c#asp.netfileserver.mappath

Closing and releasing the file after use


 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;

When used again the error is:

The process cannot accsess the file because another process is using the file

How to release the use of the file to enable reuse?


Solution

  • You need to use this pattern everywhere you are working with the file:

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