Delete the last instance of a certain string from a text file without changing the other instances of the string

c#, regex, replace, string, text

Solution

var needle = "M6T1";
var ix = str.LastIndexOf(needle);
str = str.Substring(0, ix) + str.Substring(ix + needle.Length);

Problem

I have a C# program where I am using a lot of RegEx.Replace to replace text in my text file. Here is my problem. In my text file, I have a code such as "M6T1". This code is listed in numerous places in the text file. However, I only want to delete it from the bottom (last instance) in the text file. There will always be a "M6T1" at the bottom of the text file, but it is not always the last line. It could be the 3rd line from the bottom, the 5th line from the bottom etc. I only want to get rid of the last instance of "M6T1" so RegEx.Replace won't work here. I don't want to interfer with the other "M6T1"'s in the other locations in the text file. Can someone please give me a solution to this problem? Thanks

Original source