title: File cannot be accessed because it is being used by another program
body: <p>I am trying to remove the space at the end of line and then that line will be written in another file.</p>
  
  <p>But when the program reaches to <code>FileWriter</code> then it gives me the following error</p>
  
  <blockquote>
    <p>Process can't be accessed because it is being used by another process.</p>
  </blockquote>
  
  <p>The Code is as below.</p>
  
  <pre><code>private void FrmCounter_Load(object sender, EventArgs e)
  {
          string[] filePaths = Directory.GetFiles(@"D:\abc", "*.txt", SearchOption.AllDirectories);
          string activeDir = @"D:\dest";
          System.IO.StreamWriter fw;
          string result;
  
          foreach (string file in filePaths)
          {
              result = Path.GetFileName(file);
              System.IO.StreamReader f = new StreamReader(file);
              string newFileName = result;
              // Combine the new file name with the path
              string newPath = System.IO.Path.Combine(activeDir, newFileName);
              File.Create(newPath);
  
              fw = new StreamWriter(newPath);
  
              int counter = 0;
              int spaceAtEnd = 0;
              string line;
  
              // Read the file and display it line by line.
              while ((line = f.ReadLine()) != null)
              {
                  if (line.EndsWith(" "))
                  {
                      spaceAtEnd++;
                      line = line.Substring(0, line.Length - 1);
                  }
                  fw.WriteLine(line);
                  fw.Flush(); 
                  counter++;
              }
  
              MessageBox.Show("File Name : " + result);
              MessageBox.Show("Total Space at end : " + spaceAtEnd.ToString());
              f.Close();
              fw.Close();
          }
  }
  </code></pre>