简体   繁体   English

以文本形式读取文件的一部分,以二进制形式读取文件的一部分

[英]Read part of a file as text and part as binary

I have a file done like this 我有一个这样的文件

10 NDI 27 2477 6358 4197 -67 0 VVFAˆ ÿÿÿÿ

The last column is binary. 最后一列是二进制。 I have to read this file, the problem is that I can not read it as a text because in some lines the last columns has a new line character and thus I wouldn't read the entire line. 我必须读取该文件,问题是我无法将其作为文本读取,因为在某些行中,最后几列具有换行符,因此,我不会读取整行。 Then I should read it as a binary file, but then how can I retrieve the first and the third column? 然后,我应该将其读取为二进制文件,但是如何检索第一列和第三列? I tried by reading bytes in this way: 我尝试通过这种方式读取字节:

byte[] lines1 = System.IO.File.ReadAllBytes("D:\\dynamic\\ap1_dynamic\\AP_1.txt");

And then convert it into string with 然后将其转换为字符串

 for (i = 0; i < lines1.Length; i++) {
       Convert.ToString(lines1[i],2);
 }

but then it reads everything as 0 and 1.. I would like to read the first 8 columns as text, while the last one as binary.. 但随后它将所有内容读取为0和1。我想将前8列读取为文本,而将最后8列读取为二进制。

I am using Visual Studio 2013, C#. 我正在使用Visual Studio 2013,C#。

Reading the file as binary is correct, as you can convert part of the binary data to text. 以二进制形式读取文件是正确的,因为您可以将部分二进制数据转换为文本。 In this context binary means bytes. 在这种情况下,二进制表示字节。

Converting the bytes to binary is not what you want to do. 将字节转换为二进制不是您想要的。 In this context binary means text representation in base 2, but you don't want a text representation of the data. 在这种情况下,二进制表示以2为基础的文本表示形式,但您不希望数据以文本表示形式。

If the lines are fixed length, you can do something like this to read the values: 如果行是固定长度,则可以执行以下操作来读取值:

int lineLen = 70; // correct this with the actual length
int firstPos = 0;
int firstLen = 3; // correct with actual length
int thirdPos = 15; // correct with actual position
int thirdLen = 3; // correct with actual length
int lastPos = 60; // correct with actual position
int lastLen = 10; // correct with actual length

int lines = lines.length / lineLength;
for (int i = 0; i < lines; i++) {
  int first = Int32.Parse(Encoding.UTF8.GetString(i * lineLen + firstPos, firstLen).Trim());
  int third = Int32.Parse(Encoding.UTF8.GetString(i * lineLen + thirdPos, thirdLen).Trim());
  byte[] last = new byte[lastLen];
  Array.Copy(lines1, i * lineLen + lastPos, last, 0, lastLen);
  // do something with the data in first, third and last
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM