Question

I am trying read an write to a text file in a C# application using the following code

using (System.IO.StreamReader rd = new System.IO.StreamReader(path))
{
    using (System.IO.StreamWriter wr = new System.IO.StreamWriter(path))
    {
        string line = null;
        while ((line = rd.ReadLine()) != null)
        {
            if (String.Compare(line, active_user) == 0)
            {
               //do nothing
            }
            else
            {
                wr.WriteLine(active_user);
            }

        }
    }                                     
}

Even though I am using disposable objects, still threw me the error

The process cannot access the file 'path' because it is being used by another process.

Did I go wrong anywhere?

Était-ce utile?

La solution 2

You're reading and writing to the file at the same time. Try making a list of the strings you need to write and then write them after you're finished reading.

Something like this:

List<string> toWrite = new List<string>();

using (System.IO.StreamReader rd = new System.IO.StreamReader(path))
{
    string line = null;
    while ((line = rd.ReadLine()) != null)
    {
        if (String.Compare(line, active_user) != 0) //simplified your logic
        {
            toWrite.Add(active_user);
        }

    }

}
File.WriteAllLines(path, toWrite);

Autres conseils

You're reading from the file at the path defined in variable path while trying to write to it at the same time.

While writing, the reader is still in scope and accessing the file,that's the reason you are getting this error.

When reading and writing to the same file don't open it in two different instances.

...like opening the car door for two people to get in. You can only open it once - you need to close before you can open it again. However, you can leave it open for both to get in.

In the following example: You open the stream (one time) Then you let the writer and the reader have access to the single instance of the open file. When they are both done, then you can close the file.

Note: In a more complex scenario like multithreading - you will need to implement thread safety to keep the reader and writer from trying to read and write at the same time. ...but for your example the below should suffice.

        using (System.IO.Stream stream = System.IO.File.Open(path, System.IO.FileMode.Open))
        {
            using (System.IO.StreamReader rd = new System.IO.StreamReader(stream))
            {
                using (System.IO.StreamWriter wr = new System.IO.StreamWriter(stream))
                {
                    string line = null;
                    while ((line = rd.ReadLine()) != null)
                    {
                        if (String.Compare(line, active_user) == 0)
                        {
                            //do nothing
                        }
                        else
                        {
                            wr.WriteLine(active_user);
                        }
                    }
                }
            }
        }

Despite other posts there is nothing wrong with reading from a file and writing into it "at the same time". The key to understanding the problem is the MODE which is used when OPENING the file.

have a look at a more explicit variant of your code:

        using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
        {
            using (StreamReader rd = new StreamReader(fileStream))
            {
                using (StreamWriter wr = new StreamWriter(fileStream))
                {
                    string line = null;
                    while ((line = rd.ReadLine()) != null)
                    {
                        if (String.Compare(line, active_user) == 0)
                        {
                            //do nothing
                        }
                        else
                        {
                            wr.WriteLine(active_user);
                            //If you flush what you write then you will see it via the reader.
                            //Comment out for better performance. Keep in mind, that writing
                            //into a file will lead to occasional flush which affects the
                            //reader. Implicit Flush happens once you write more than the
                            //buffer of the writer suggests.
                            wr.Flush();
                        }

                    }
                }
            }                 
        }

As you can see, it is different from your code in the way the file is opened. I just prefer to explicitly specify the mode I open file with. It appears that the StreamReader implicitly opens the file without "sharing" i.e. does not allow others to open it and this is OK because it wants to protect you from getting unexpected results. Hereby this implicit method does not fit your slightly more "complicated" scenario. Opening the file explicitly does the trick. Note that File.Open allows you to open a file and still allow other threads (other applications) open the file. It's all up to you.

Now to the logic of your code. StreamReader reads the stream from the beginning. StreamWriters appens to the end of contents of the stream. Both keep and maintain their own stream positions. Thus the code will append a line containing the "active_user" for each line of your file which does not contain "active_user". I can not imagine a practical reason for that.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top