Share via


How can I open and read a file, delete it, then create a new, updated, file with the same name?

Question

Monday, September 9, 2013 12:46 AM

This can't really be that hard. I need to open a text file and change one value in it. But no matter what I've tried, I get an err msg about the file being alread in use after opening it.

I've asked a question on Stack Overflow (http://stackoverflow.com/questions/18669796/why-is-my-attempt-to-write-to-a-file-thwarted), but it was marked as a duplicate, although the supposed duplicate does not help me.

Besides the code listed there, I've most recently tried this:

            string ticklerFile = "awardUpdateDates.txt";
            string readLine;
            List<string> lions = new List<string>(); 

            StreamReader stromLeser = new StreamReader(ticklerFile);
            readLine = stromLeser.ReadLine();
            while (readLine != null)
            {
                if (readLine.ToUpper().Contains("PULITZER"))
                {
                    lions.Add(string.Format("Pulitzer~{0}", DateTime.Now.ToString("d")));
                }
                else
                {
                    lions.Add(readLine);
                }
                readLine = stromLeser.ReadLine();
            }
            stromLeser.Close();

            File.Delete(ticklerFile); <-- this throws the exception

            StreamWriter stromSchreiber = new StreamWriter(ticklerFile);
            foreach (string l in lions)
            {
                stromSchreiber.WriteLine(l);
            }
            stromSchreiber.Close();

...but I still get the System.IOException "The process cannot access the file 'Bla.txt' because it is being used by another process."

As I said, all I want to do is open a text file, read its values, find a particular line in the file, and replace part of that line with something different, then update the file by either overwriting the old line with the new line, or by deleting the old file and writing a new file with the same name. Yet when I try to delete the file, I get the err msg listed above.

I tried this, too, and still get the same exception, even though 

            string[] fileContents = File.ReadAllLines(ticklerFile);
            for (int i = 0; i < fileContents.Length; i++)
            {
                readLine = fileContents[i];
                if (readLine.ToUpper().Contains("PULITZER"))
                {
                    lions.Add(string.Format("Pulitzer~{0}", DateTime.Now.ToString("d")));
                    DateTime.Now.ToString("d")));
                }
                else
                {
                    lions.Add(readLine);
                }
            }

                File.Delete(ticklerFile);

                StreamWriter stromSchreiber = new StreamWriter(ticklerFile);
                foreach (string l in lions)
                {
                    stromSchreiber.WriteLine(l);
                }
                stromSchreiber.Close();

...even though File.ReadAllLines() supposedly closes the file after doing its work.

All replies (6)

Monday, September 9, 2013 5:44 AM ✅Answered | 1 vote

Is the file you are working with your file or file created by some other process?

Take a look at the first answer from this link: http://stackoverflow.com/questions/860656/using-c-how-does-one-figure-out-what-process-locked-a-file

Use 'GetProcessesLockingFile' before your File.Delete call to get the info which process is locking the file.
Eventually you can write a small loop routine where you can try to open and close the file with the FileShare.None flag which will throw an exception when the file is locked by some other process. Keep it looping until you stop getting the exception. 

If it's a file that you created through your project, check your project if you are not keeping it open somewhere else.

**Josip Habjan     ** http://habjan.blogspot.com


Monday, September 9, 2013 1:38 PM ✅Answered

My bad - I was opening the file in the main form,and then not explicitly closing it. Changing it to this:

using (StreamReader file = new StreamReader("awardUpdateDates.txt"))

from this:

StreamReader file = new StreamReader("awardUpdateDates.txt");

...in the main form solves the problem.


Monday, September 9, 2013 1:09 AM | 1 vote

I find this thread interesting, and you might find it interesting too. :) It may be that GC is in the way.

http://bytes.com/topic/c-sharp/answers/237536-streamwriter-streamreader-closing-files


Monday, September 9, 2013 3:15 AM | 1 vote

I ran the first block code you created and it did not cause an exception.  Is the file you are processing a very large file?

I added some code to hopefully make it better for you with some validation

string ticklerFile = "awardUpdateDates.txt";            string readLine;            List<string> lions = new List<string>();            if (File.Exists(ticklerFile))            {                using (var stromLeser = new StreamReader(ticklerFile))                {                    readLine = stromLeser.ReadLine();                    while (readLine != null)                    {                        if (readLine.ToUpper().Contains("PULITZER"))                        {                            lions.Add(string.Format("Pulitzer~{0}", DateTime.Now.ToString("d")));                        }                        else                        {                            lions.Add(readLine);                        }                        readLine = stromLeser.ReadLine();                    }                    stromLeser.Close();                }                File.Delete(ticklerFile);                using (var stromSchreiber = new StreamWriter(ticklerFile))                {                    foreach (string l in lions)                    {                        stromSchreiber.WriteLine(l);                    }                    stromSchreiber.Flush();                    stromSchreiber.Close();                }            }

Monday, September 9, 2013 4:26 AM

No, it's a very small file.

Thanks, I'll try it out.


Monday, September 9, 2013 4:31 AM

I still get, "System.IO.IOException was unhandled
  HResult=-2147024864
  Message=The process cannot access the file 'C:\AwardWinnersOnlyOriginal12UpdateUtil\AWO12OriginalUpdateUtil\bin\Debug\awardUpdateDates.txt' because it is being used by another process."