Using StreamReader and StreamWriter to modify files

I am trying to use StreamReader and StreamWriter to open a text file (fixed width) and to modify a few specific data columns. I have dates with the following format that will be converted to packed COMP-3 fields.

020100718F 020100716F 020100717F 020100718F 020100719F 

I want to be able to read a file in the form of a date using StreamReader, then convert them to packed fields (5 characters), and then output them using StreamWriter. However, I did not find a way to use StreamWriter to access a specific position and start to wonder if this is possible.

I have the following snip-it code.

 System.IO.StreamWriter writer; this.fileName = @"C:\Test9.txt"; reader = new System.IO.StreamReader(System.IO.File.OpenRead(this.fileName)); currentLine = reader.ReadLine(); currentLine = currentLine.Substring(30, 10); //Substring Containing the Date reader.Close(); ... // Convert currentLine to Packed Field ... writer = new System.IO.StreamWriter(System.IO.File.Open(this.fileName, System.IO.FileMode.Open)); writer.Write(currentLine); 

I currently have the following:

 After: !@ #$%0718F 020100716F 020100717F 020100718F 020100719F !@ #$% = Ascii Characters SO can't display 

Any ideas? Thanks!

UPDATE Packed Field Information COMP-3

Packed fields are used by COBOL systems to reduce the number of bytes required for files in files. See the following SO publication for more information: Here

Here is a picture of the next date "20120123", packaged on COMP-3. This is my final result, and I included it because I was not sure that this would affect the possible answers.

Picture of the following date 20120123 packed

My question is: how to get StreamWriter to dynamically replace the data inside the file and change the length of the lines?

+4
source share
3 answers

I was always better off reading the input file, filtering / processing the data and writing the output to a temporary file. When finished, delete the source file (or make a backup) and copy the temporary file. Thus, you have not lost half of your input file in case something goes wrong in the middle of processing.

+2
source

You should probably use Stream directly (possibly FileStream ). This will allow you to change position.

However, you cannot resize records this way, at least not in a row. You can have one reading of the stream from the source file, and another - writing to a new, converted copy of the file.

+1
source

However, I did not find a way to use StreamWriter to move to a specific position, and I start to wonder if possible.

You can use the StreamWriter.BaseStream.Seek method

 using (StreamWriter wr = new StreamWriter(File.Create(@"c:\Temp\aaa.txt"))) { wr.Write("ABC"); wr.Flush(); wr.BaseStream.Seek(0, SeekOrigin.Begin); wr.Write("Z"); } 
0
source

Source: https://habr.com/ru/post/1393824/


All Articles