Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

c# - 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 columns of data. I have dates with the following format that are going to be converted to packed COMP-3 fields.

020100718F
020100716F
020100717F
020100718F
020100719F

I want to be able to read in the dates form a file using StreamReader, then convert them to packed fields (5 characters), and then output them using StreamWriter. However, I haven't found a way to use StreamWriter to right to a specific position, and beginning to wonder if is possible.

I have the following code snip-it.

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);

Currently what I have does the following:

After:
!@#$%0718F
020100716F
020100717F
020100718F
020100719F 

!@#$% = Ascii Characters SO can't display 

Any ideas? Thanks!

UPDATE Information on Packed Fields COMP-3

Packed Fields are used by COBOL systems to reduce the number of bytes a field requires in files. Please see the following SO post for more information: Here

Here is Picture of the following date "20120123" packed in COMP-3. This is my end result and I have included because I wasn't sure if it would effect possible answers.

Picture of the following date 20120123 packed

My question is how do you get StreamWriter to dynamically replace data inside a file and change the lengths of rows?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have always found it better to to read the input file, filter/process the data and write the output to a temporary file. After finished, delete the original file (or make a backup) and copy the temporary file over. This way you haven't lost half your input file in case something goes wrong in the middle of processing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...