Replace the character of the nth position

I am writing this program to replace a character at the nth position of a line in a text file. My text file consists of the following content -

the quick brown fox jumped over the lazy dog the quick brown fox jumped over the lazy dog the quick brown fox jumped over the lazy dog the quick brown fox jumped over the lazy dog 

And here is the code output -

 thehuick brown fox jumped over the lazy dog 

The above result is not the one I wanted. Only one line was updated, the rest were not found in the file.

Here is my complete code in C #

  var txtFiles = Directory.GetFiles(@"E:\PROJ\replaceY\replaceY\", "*.txt"); foreach (string currentFile in txtFiles) { string[] lines = File.ReadAllLines(currentFile); foreach (string line in lines) { var theString = line; var aStringBuilder = new StringBuilder(theString); aStringBuilder.Remove(3, 2); aStringBuilder.Insert(3, "h"); theString = aStringBuilder.ToString(); using (StreamWriter outfile = new StreamWriter(currentFile)) { outfile.Write(theString.ToString()); } Console.WriteLine(theString); Console.ReadKey(); } } 

Where am I wrong? Please, help!

+6
source share
4 answers

Because your logic says:

  • for each file
    • open file
    • for each line in the file
      • process it
      • open the file for writing
      • write a line

This means that you are overwriting the file with the last line again. At the end of this file, each file contains only one line: the last.

You want to do something like this:

 static void Main(string[] args) { foreach ( string fileName in args ) { string tempFileName = Path.GetTempFileName() ; using ( Stream tmpFile = File.Open( tempFileName , FileMode.OpenOrCreate , FileAccess.Write , FileShare.None ) ) using ( StreamWriter output = new StreamWriter( tgtFile , Encoding.Default ) ) using ( Stream srcFile = File.Open( fileName , FileMode.Open , FileAccess.ReadWrite , FileShare.None ) ) using ( StreamReader input = new StreamReader( srcFile , Encoding.Default , true ) ) { string line ; while ( null != (line=input.ReadLine()) ) { output.Write( line.Substring(0,3) ) ; output.Write( 'h' ) ; output.WriteLine( line.Substring(5) ) ; } } string backupFileName = string.Format( "{0}.{1:yyyy-MM-dd.HHmmss}.bak" , fileName , DateTime.Now ) ; File.Move( fileName , backupFileName ) ; File.Move( tempFileName , fileName ) ; File.Delete( backupFileName ) ; } return; } 

You need to add some try/catch/finally exception handling to deal with cases when something goes south with the file, so you can return this file to its original state.

Other parameters:

  • open the file for reading.
  • slurp in all contents with File.ReadAllLines() or equivalent
  • convert strings as you like
  • open the source file for writing
  • drag the converted content to the source file.

Which brings you to something like this:

 static void Main(string[] args) { foreach ( string fileName in args ) { string[] lines = File.ReadAllLines( fileName ) ; for ( int i = 0 ; i < lines.Length ; ++i ) { lines[i] = ApplyTransformHere( lines[i] ) ; } File.WriteAllLines( fileName , lines ) ; } return; } 
+6
source

I created a boolean application at the beginning of each new file that is set to false, so it creates a new file for the first line, and then sets append = true, so every subsequent line is added to

 var txtFiles = Directory.GetFiles(@"E:\PROJ\replaceY\replaceY\", "*.txt"); foreach (string currentFile in txtFiles) { var append = false; string[] lines = File.ReadAllLines(currentFile); foreach (string line in lines) { var theString = line; var aStringBuilder = new StringBuilder(theString); aStringBuilder.Remove(3, 2); aStringBuilder.Insert(3, "h"); theString = aStringBuilder.ToString(); using (StreamWriter outfile = new StreamWriter(currentFile, append)) { outfile.Write(theString.ToString() + Environment.NewLine); } append = true; } } 
+3
source

On the side of the note, but still connected. Have you decided to use Regex to replace all lines?

https://regex101.com/r/aC6cY1/1

Like /(?<=^.{4,4})./gm

 string input = "";//your sample text above string pattern = "(?<=^.{4,4})."; string replacement = "h"; Regex rgx = new Regex(pattern, RegexOptions.Multiline); string result = rgx.Replace(input, replacement); 

As for your problem, I would:

 var txtFiles = Directory.GetFiles(@"E:\PROJ\replaceY\replaceY\", "*.txt"); foreach (string currentFile in txtFiles) { using (StreamReader sr = new StreamReader(currentFile)) { string input = sr.ReadToEnd(); string pattern = "(?<=^.{4,4})."; string replacement = "h"; Regex rgx = new Regex(pattern, RegexOptions.Multiline); string result = rgx.Replace(input, replacement); using (StreamWriter outfile = new StreamWriter(currentFile, append)) { outfile.Write(result); } } } 
+1
source

Take a second foreach loop entry, replace it with an array string. then write an array of strings to the files in the first foreach loop. what should solve your logical problem.

0
source

All Articles