使用 StreamReader 和 StreamWriter 修改文件 [英] Using StreamReader and StreamWriter to Modify Files

查看:75
本文介绍了使用 StreamReader 和 StreamWriter 修改文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 StreamReader 和 StreamWriter 打开文本文件(固定宽度)并修改一些特定的数据列.我有以下格式的日期,这些日期将被转换为压缩的 COMP-3 字段.

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

我希望能够使用 StreamReader 从文件中读取日期,然后将它们转换为压缩字段(5 个字符),然后使用 StreamWriter 输出它们.但是,我还没有找到使用StreamWriter向右到特定位置的方法,开始怀疑是否可能.

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.

我有以下代码片段.

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

目前我所做的如下:

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

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

有什么想法吗?谢谢!

更新关于压缩字段 COMP-3 的信息

UPDATE Information on Packed Fields COMP-3

COBOL 系统使用压缩字段来减少字段在文件中所需的字节数.有关详细信息,请参阅以下 SO 帖子:此处

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

这是以下日期20120123"的图片,封装在 COMP-3 中.这是我的最终结果,我将其包括在内,因为我不确定它是否会影响可能的答案.

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.

我的问题是如何让 StreamWriter 动态替换文件内的数据并更改行的长度?

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

推荐答案

我一直发现读取输入文件、过滤/处理数据并将输出写入临时文件更好.完成后,删除原始文件(或进行备份)并将临时文件复制过来.这样您就不会丢失一半的输入文件,以防在处理过程中出现问题.

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.

这篇关于使用 StreamReader 和 StreamWriter 修改文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆