2

I am trying to remove the space at the end of line and then that line will be written in another file.

But when the program reaches to FileWriter then it gives me the following error

Process can't be accessed because it is being used by another process.

The Code is as below.

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();
        }
}
Khilen Maniyar
  • 2,519
  • 7
  • 31
  • 35
  • Well, the file is obviously opened by another program. Perhaps try to close it if it is opened as a window? Perhaps another program has it opened just like you are trying to? – SimpleVar Jul 31 '12 at 12:08
  • At a guess, because you setting activeDir and filePaths to the same directory, you are trying to write to the same file you are reading from. – StuartLC Jul 31 '12 at 12:10
  • Well i tried another directory also.. but same error – Khilen Maniyar Jul 31 '12 at 12:11

5 Answers5

2

File.Create itself returns a stream.

Use that stream to write file. Reason you are receiving this error is because Stream returned by File.Create is open and you are trying to open that file again for write.

Either close the stream returned by File.Create or better use that stream for file write or use

Stream newFile = File.Create(newPath);
fw = new StreamWriter(newFile);
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
ZafarYousafi
  • 8,640
  • 5
  • 33
  • 39
1

Even though you solved your initial problem, if you want to write everything into a new file in the original location, you can try to read all of the data into an array and close the original StreamReader. Performance note: If your file is sufficiently large though, this option is not going to be the best for performance.

And you don't need File.Create as the StreamWriter will create a file if it doesn't exist, or overwrite it by default or if you specify the append parameter as false.

result = Path.GetFileName(file);
String[] f = File.ReadAllLines(file);  // major change here... 
                                       //  now f is an array containing all lines 
                                       //  instead of a stream reader

using(var fw = new StreamWriter(result, false))
{
    int counter = f.Length; // you aren't using counter anywhere, so I don't know if 
                            //  it is needed, but now you can just access the `Length`  
                            //  property of the array and get the length without a 
                            //  counter

    int spaceAtEnd = 0;

    // Read the file and display it line by line.
    foreach (var item in f)
    {
        var line = item;

        if (line.EndsWith(" "))
        {
            spaceAtEnd++;
            line = line.Substring(0, line.Length - 1);
        }
        fw.WriteLine(line);
        fw.Flush(); 
    }
}

MessageBox.Show("File Name : " + result);
MessageBox.Show("Total Space at end : " + spaceAtEnd.ToString());

Also, you will not remove multiple spaces from the end of the line using this method. If you need to do that, consider replacing line = line.Substring(0, line.Length - 1); with line = line.TrimEnd(' ');

psubsee2003
  • 8,563
  • 8
  • 61
  • 79
0

You have to close any files you are reading before you attempt to write to them in your case.

Axxelsian
  • 787
  • 3
  • 9
  • 25
0

EDIT:

Zafar is correct, however, maybe this will clear things up.

Because File.Create returns a stream.. that stream has opened your destination file. This will make things clearer:

File.Create(newPath).Close();

Using the above line, makes it work, however, I would suggest re-writing that properly. This is just for illustrative purposes.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
0

Write stream in using statement like:

using (System.IO.StreamReader f = new StreamReader(file))
{
   //your code goes here
}
Adil Mammadov
  • 8,476
  • 4
  • 31
  • 59