title: How can close the image file using FileStream
body: <p>I need to make image from canvas and from internet I find this code who works perfect. Is make the image and is good. But now I need to add some text in this new image and i think this is the problem. Sometimes is working, sometimes is throw me this exception. How can I close the image and change the image again. Or how can I change the image without is have exception.</p>
  
  <pre><code>int width = (int)(SystemParameters.PrimaryScreenWidth * 0.75);
  int height = (int)canvas.Height;
  
  RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
  width, (int)canvas.Height, 96d, 96d, PixelFormats.Pbgra32);
  // needed otherwise the image output is black
  canvas.Measure(new System.Windows.Size(width, height));
  canvas.Arrange(new Rect(new System.Windows.Size(width, height)));
  
  renderBitmap.Render(canvas);
  
  //JpegBitmapEncoder encoder = new JpegBitmapEncoder();
  PngBitmapEncoder encoder = new PngBitmapEncoder();
  encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
  
  using (FileStream file = File.Create(filename))
  {
       encoder.Save(file);
  }
  </code></pre>
  
  <p>This is what Exception I have:</p>
  
  <blockquote>
    <p>The process cannot access the file 'image.png' because it is being used by another process.</p>
  </blockquote>
  
  <p>I try with <code>file.Close()</code>, I try without <code>file.Close()</code> <code>filename</code> is path to image file who create and then used and try delete</p>
  
  <p>Here and my code This code is running every 1 second.</p>
  
  <pre><code>private void CreateSaveBitmap(Canvas canvas, string filename, string sensor)
  {
      int width = (int)(SystemParameters.PrimaryScreenWidth * 0.75);
      int height = (int)canvas.Height;
  
      RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
           width, (int)canvas.Height,
           96d, 96d, PixelFormats.Pbgra32);
      // needed otherwise the image output is black
      canvas.Measure(new System.Windows.Size(width, height));
      canvas.Arrange(new Rect(new System.Windows.Size(width, height)));
  
      renderBitmap.Render(canvas);
  
      //JpegBitmapEncoder encoder = new JpegBitmapEncoder();
      PngBitmapEncoder encoder = new PngBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
  
      using (FileStream file = File.Create(filename))
      {
          encoder.Save(file);
          file.Close();
      }
  
      string head = SetHeadForPrintImage(sensor);
      Bitmap bmp = new Bitmap(filename);
      Graphics g = Graphics.FromImage(bmp);
  
      g.DrawString(head, new System.Drawing.Font("Tahoma", 12f, System.Drawing.FontStyle.Regular), System.Drawing.Brushes.Black, new PointF(200, 0));
  
      bmp.SetResolution(300, 300);
      File.Delete(filename); // throw me exception
      File.Delete(@".\Print\" + sensor + ".jpg");
      bmp.Save(@".\Print\" + sensor + ".jpg");
  }
  </code></pre>