tags:

views:

283

answers:

2

Code:

        String tempFile = Path.GetTempFileName(), read = "";
        TextReader pending = new StreamReader("c:\\pending.txt");
        TextWriter temp = new StreamWriter(tempFile);

        read = pending.ReadLine();

        while ((read = pending.ReadLine()) != null)
        {
            temp.WriteLine(read);
        }

        pending.Close();
        temp.Close();

        File.Delete("c:\\pending.txt");
        File.Move(tempFile, "c:\\pending.txt");

The pending.txt file is created when the program starts if it doesn't exist. This code deletes the first line of the file. When I debug the code, I notice that the

        File.Move(tempFile, "c:\\pending.txt");

locks the file and I cannot write to it anymore.

+1  A: 

You should close your StreamReader and StreamWriter in using statements, like this:

String tempFile = Path.GetTempFileName(), read = "";
using(TextReader pending = new StreamReader("c:\\pending.txt"))
using(TextWriter temp = new StreamWriter(tempFile))
{

    read = pending.ReadLine();

    while ((read = pending.ReadLine()) != null)
    {
        temp.WriteLine(read);
    }
}

File.Delete(@"c:\pending.txt");
File.Move(tempFile, @"c:\pending.txt");
SLaks
I'd also suggest that if you're copying a file yourself, doing so in fixed size blocks (4K, 8K?) is more efficient than line-by-line.
Andrew
I tried this, but it still gives the same results. What's happening is, I have windows 7 by the way, as soon as the program hits "File.Move" I get a lock image on the icon of the file. After this, I cannot write anything to the file. It looks like it writes, but the file is not changed when I open it through windows explorer. I get no errors saying file in use either.
Mtlca401
A: 

Never mind. Windows Explorer stills shows a locked icon, but the rest of my code was wrong. sorry. but thanks for the using tip. I have to look more into the readBlock.

Mtlca401