1

I am in a fight with overwriting of a text file with some of changes using a console application. Here I am reading the file line by line. Can any one help me.

StreamReader sr = new StreamReader(@"C:\abc.txt");
string line;
line = sr.ReadLine();

while (line != null)
{
  if (line.StartsWith("<"))
  {
    if (line.IndexOf('{') == 29)
    {
      string s = line;
      int start = s.IndexOf("{");
      int end = s.IndexOf("}");
      string result = s.Substring(start+1, end - start - 1);
      Guid g= Guid.NewGuid();
      line = line.Replace(result, g.ToString());
      File.WriteAllLines(@"C:\abc.txt", line );
    }
  }
  Console.WriteLine(line);

  line = sr.ReadLine();
}
//close the file
sr.Close();
Console.ReadLine();

Here I am getting the error file is already open by another process.

Please help me, anyone. Main task is to overwrite the same texfile with modifications

John Willemse
  • 6,386
  • 7
  • 28
  • 44
user2477724
  • 121
  • 1
  • 4
  • 10
  • You should read all lines using the streamreader, store them in a collection of lines, and then close the streamreader before you start writing to the file again. – John Willemse Dec 20 '13 at 12:19

3 Answers3

0

You need a single stream, open it for both reading and writing.

FileStream fileStream = new FileStream(
      @"c:\words.txt", FileMode.OpenOrCreate, 
      FileAccess.ReadWrite, FileShare.None);

now you can use fileStream.Read() and fileStream.Write() methods

please see this link for extended discussion

How to both read and write a file in C#

Community
  • 1
  • 1
gaurav5430
  • 9,899
  • 5
  • 32
  • 73
0

The problem is that you're trying to write to a file that is used by the StreamReader. You have to close it or - better - use the using-statement which disposes/closes it even on error.

using(StreamReader sr = new StreamReader(@"C:\abc.txt"))
{
    // ...
}
File.WriteAllLines(...);

File.WriteAllLines also writes all lines to the file not only the currrent line, so it's pointless to do it in the loop.

Can i suggest you a different method to read the lines of a text-file? You can use File.ReadAllLines which reads all lines into a string[] or File.ReadLines which works similar to a StreamReader by reading all lines lazily.

Here's a version doing the same but using a ( more readable?) LINQ query:

var lines = File.ReadLines(@"C:\abc.txt")
    .Where(l => l.StartsWith("<") && l.IndexOf('{') == 29)
    .Select(l => 
    {
        int start = l.IndexOf("{");
        int end = l.IndexOf("}", start);
        string result = l.Substring(start + 1, end - start - 1);
        Guid g = Guid.NewGuid();
        return l.Replace(result, g.ToString());
    }).ToList();
File.WriteAllLines(@"C:\abc.txt", lines);
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
0

Problem is that you have opened the file and reading from same file at the same time you are writing in that file. But what you should do is,

  1. Read the changes from the file
  2. Close the file
  3. Write the contents back to file

So your code should be like

List<string> myAppendedList = new List<string>();
using (StreamReader sr = new StreamReader(@"C:\abc.txt"))

{
    string line;
    line = sr.ReadLine();

    while (line != null)
    {
        if (line.StartsWith("<"))
        {
            if (line.IndexOf('{') == 29)
            {
                string s = line;
                int start = s.IndexOf("{");
                int end = s.IndexOf("}");
                string result = s.Substring(start + 1, end - start - 1);
                Guid g = Guid.NewGuid();
                line = line.Replace(result, g.ToString());
                myAppendedList.Add(line);

            }
        }
        Console.WriteLine(line);

        line = sr.ReadLine();
    }
}

if(myAppendedList.Count > 0 )
    File.WriteAllLines(@"C:\abc.txt", myAppendedList);
dbw
  • 5,842
  • 2
  • 21
  • 56