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; }
source share