insert the space into Filereader

130 views Asked by At

I have to write the code to insert the space in middle of falt file.
I have text as below, each line column length should be same

123
123256
123323  

the above string should looks like

123---   
234256
987323

After 123 we need space. could you suggest how to do this.

I have loaded the file into string dr = file.ReadToEnd();

2

There are 2 answers

0
Dweeberly On

Use the string split function to split your lines at the line break (either \n or System.Environment.NewLine, depending your desires). Iterate over the returned array to Trim() each string, then use the PadRight function to produce a new string of the desired length with the desired trailing characters. Then use one of the many IO write functions to output to a new file or overwrite the existing file.

0
Tony Hopkinson On

Something like

using(FileStream input = new FileStream(inputFileName,FileMode.Open,FileAccess.Read))
{
  TextReader reader = new StreamReader(input);
  using (FileStream output = new FileStream(OutputFileName, FileMode.OpenOrCreate, FileAccess.Write))
  {
    TextWriter writer = new StreamWriter(output);
    string line;
    while ((line = reader.ReadLine()) != null)
     {
       writer.WriteLine(line.PadRight(6,' '));
     } 
  }
}

Off the top of my head this, so may be a silly in it.

Then rename outputFileName to inputFileName