0

我正在使用 C# 读取文件,我需要(有时)在输出下一个字节之前跳过几个字节。例如:

31 32 33 34 35 36 37 38 39 

我想跳过前两个(或任何给定数量)字节,然后输出下一个。问题是,使用下面的代码不会这样做,我不知道该怎么做。我需要能够在整个程序中使用“跳过”功能。如果有人可以帮助我,我将不胜感激!

        String fileDirectory = "C:\\t.txt";
        StreamReader reader = new StreamReader(fileDirectory);
        long stickNoteLength = fileDirectory.Length;

        int hexIn;
        String hex = "";

        for (int i = 0; (hexIn = reader.Read()) != -1; i++)
        {
            for (int x = 0; x < 2; x++)
            {
               hex = hexIn.ToString("X2");
            }
            MessageBox.Show(hex);
        }
4

1 回答 1

2

您的内部 for 循环x不会消耗文件中的任何字符。它实际上只是获取当前字节并连续两次将其转换为十六进制,实际上什么也没做。i它实际上是消耗字符的外部循环。你想做更多这样的事情:

for (int i = 0; (hexIn = reader.Read()) != -1; i++)
{
    if (i >= 2)
    {
        hex = hexIn.ToString("X2");
        MessageBox.Show(hex);
    }
}

尽管只使用该Seek函数直接跳转到您接下来要阅读的位置会更有效:

reader.BaseStream.Seek(2, SeekOrigin.Current);  // jump two characters forward
于 2011-05-16T04:37:51.200 回答