Dujskan
Dujskan

Reputation: 125

(StreamWriter) The process cannot access the file because its being used by another process

Hi why dosent this work?

using (StreamWriter sw = File.CreateText(path))
{
    for (int i = 0; i < 100; i++)
    {
        sw.WriteLine(i.ToString());
    }
    int count = File.ReadLines(path).Count();
    sw.WriteLine(count.ToString());
}

I got this error message: "The process cannot access the file because its being used by another process."

So i figgured i had to put it like this:

using (StreamWriter sw = File.CreateText(path))
{
    for (int i = 0; i < 100; i++)
    {
        sw.WriteLine(i.ToString());
    }
}

using (StreamWriter sw = File.CreateText(path))
{
    int count = File.ReadLines(path).Count();
    sw.WriteLine(count.ToString());
}

But i get the same error. Iam so bad at this, someone please help me :)

Upvotes: 0

Views: 4554

Answers (2)

apomene
apomene

Reputation: 14389

            using (StreamWriter sw = File.CreateText(path))
            {
                for (int i = 0; i < 100; i++)
                {
                    sw.WriteLine(i.ToString());
                }

            }

            int count = File.ReadLines(path).Count();
            using (StreamWriter sw = File.CreateText(path))
            {

                sw.WriteLine(count.ToString());
            }

Upvotes: 0

thumbmunkeys
thumbmunkeys

Reputation: 20764

When you call ReadLines() the file is already open due to the open StreamWriter.

You have to perform the actions sequentially:

        int count = File.ReadLines(path).Count();
        using (StreamWriter sw = File.CreateText(path))
        {            
            sw.WriteLine(count.ToString());
        }

Upvotes: 3

Related Questions