Search code examples
c#edix12

Why is this code not replacing data in a text file?


I'm working on a small app which should read a file (ANSI 835) and replace data at certain positions with generic data. Basically I'm trying to scrub a person's first and last name from the file.

The line I'm searching for that contains the name looks like this:

NM1*QC*1*Doe*John*R***MI*010088307    01~

My code looks like this:

string[] input_file = (string[])(e.Data.GetData(DataFormats.FileDrop));
string output_file = @"c:\scrubbed.txt";

foreach (string file in input_file)
{
    string[] lines = File.ReadAllLines(file);

    foreach (string line in lines)
    {
        if (line.StartsWith("NM1*QC"))
        {
            line.Split('*')[1] = "Lastname";
            line.Split('*')[2] = "Firstname";
        }
    }

    File.WriteAllLines(output_file, lines);
}

The File.WriteAllLines works, but the data isn't being changed. I'm trying to get any line that starts with NM1*QC to look like this:

NM1*QC*1*Lastname*Firstname*R***MI*010088307    01~

There are many lines in the file that start with NM1*QC. What's the proper way to 'find and replace' and then create a new file in this situation?

As always, thanks for your time!


Solution

  • The calls to String.Split return variables that you neither capture, nor use, they do not change the underlying string. So your code equates to this:

     if (line.StartsWith("NM1*QC"))
     {
         string[] split1 = line.Split('*')[1] = "Lastname";
         string[] split2 = line.Split('*')[2] = "Firstname";
     }
    

    You would need to take the results of split1 and split2 and use those to recreate your string. Here is how I would re-write your code:

    string[] input_file = (string[])(e.Data.GetData(DataFormats.FileDrop));
    string output_file = @"c:\scrubbed.txt";
    foreach (string file in input_file)
    {
        string[] lines = File.ReadAllLines(file);
    
        for (int i=0; i < lines.length; i++)
        {
            string line = lines[i];
            if (line.StartsWith("NM1*QC"))
            {
                string[] values = line.Split('*');
                values[1] = "Lastname";
                values[2] = "Firstname";
                lines[i] = String.Join("*", values);
            }
        }
    
        File.WriteAllLines(output_file, lines);
    }
    

    Notice I am recombining the individual values using the String.Join method, and inserting the new string back into the array of lines. That will then get written out as you expect.