繁体   English   中英

使用BinaryReader c#从头读取文件到特定位置

[英]read file from beginning to a particular position using BinaryReader c#

我已经使用BinaryWriter将数据保存在文件中。

现在,我想使用BinaryReader从该文件读取数据(从特定位置开始)。

写入文件时,我在文件中间添加了一个字符串“ BREAK”。

我想从0读取到“ BREAK”之前和“ BREAK”之后,以读取C#中的OF文件结尾 请帮我。

BinaryWriter用于编写非人类可读格式的二进制文件 例如,如果您要编写基本类型,则可以以其字节表示形式(例如boolean)编写它们

因此,为了编写/读取人类可读文件,您只需使用StreamReader / StreamWriter 这样会容易得多

使用StreamReader

下面的代码段按照您的规范工作,但是如果您想改进其算法或其他功能,它仅是一个指南。 我也强烈建议您只使用StreamWriter 但是下面的代码使用BinaryWriter

namespace _16953330
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
@"The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
fox jumps over the lazy dfox jumps over the lazy dBREAK fox jumps over the lazy dfox jumps over the lazy d
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.";
            using (var stream = new FileStream("file.txt", FileMode.OpenOrCreate))
            {
                using (var writer = new BinaryWriter(stream)) //why use a BinaryWriter if you're gonna write in a human-readable format?
                {
                    writer.Write(input);
                }
            }

            string firstPart = string.Empty;
            string secondPart = string.Empty;

            StringBuilder sb = new StringBuilder();

            using (var stream = new FileStream("file.txt", FileMode.OpenOrCreate))
            {
                using (var reader = new StreamReader(stream))
                {
                    string line;
                    while (!string.IsNullOrEmpty(line = reader.ReadLine()))
                    {
                        int indexOfBreak = line.IndexOf("BREAK");
                        if (indexOfBreak == -1)
                        {
                            sb.Append(line);
                        }
                        else
                        {
                            string untilBeforeBREAK = line.Substring(0, indexOfBreak);
                            sb.Append(untilBeforeBREAK);
                            //remove the first 2 characters in the file as the BinaryWriter 
                            //writes the length of the bytes should a BinaryReader expect
                            //(if ever you want to use a binary reader which I don't understand
                            //because you are reading a HUMAN READABLE file)
                            firstPart = sb.Remove(0,2).ToString(); 

                            sb.Clear();

                            string breakUpToTheEnd = string.Empty;
                            sb.Append(line.Substring(indexOfBreak));
                            sb.Append(reader.ReadToEnd());
                            secondPart = sb.ToString();
                        }
                    }
                }
            }

            Console.WriteLine(firstPart);
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine(secondPart);

        }
    }
}

使用BinaryReader

但是,如果您真的坚持使用BinaryReaderBinaryWriter这是一种解决方案。

namespace _16953330
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] input = Encoding.ASCII.GetBytes(
@"I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryBREAKWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. I have saved data using BinaryWritter in a file. "); //just for sampling purposes, considering that what you write is NON-human-readable
            using (var stream = new FileStream("somefile.exe", FileMode.OpenOrCreate))
            {
                using (var writer = new BinaryWriter(stream))
                {
                    writer.Write(input);
                }
            }

            byte[] firstPart = null;
            byte[] secondPart = null;

            StringBuilder sb = new StringBuilder();

            string breaker = "BREAK";
            List<byte> byteList = new List<byte>();

            using (var stream = new FileStream("somefile.exe", FileMode.OpenOrCreate))
            {
                using (var reader = new BinaryReader(stream))
                {
                    while (reader.BaseStream.Position != reader.BaseStream.Length)
                    {
                        byte currentByte;
                        currentByte = reader.ReadByte();
                        if (currentByte == 'B')
                        {
                            byteList.Add(currentByte);
                            for (int i = 1; i < breaker.Length; i++)
                            {
                                currentByte = reader.ReadByte();
                                byteList.Add(currentByte);
                                //if the succeeding characters match the characters after B in BREAK
                                if ((char)currentByte == breaker[i] && i > 1)
                                {
                                    byteList.RemoveAt(byteList.Count - 1);
                                    if (i == breaker.Length - 1)
                                    {
                                        //if the for loop reaches its end and matches all characters in BREAK
                                        //remove B (which was added above) and K (added last)
                                        byteList.RemoveAt(byteList.Count - 1);
                                        byteList.RemoveAt(byteList.Count - 1);
                                        firstPart = byteList.ToArray();
                                        byteList.Clear();
                                    }
                                }
                            }
                        }
                        else
                        {
                            byteList.Add(currentByte);
                        }
                    }
                    secondPart = byteList.ToArray();
                }
            }

            Console.WriteLine(firstPart);
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine(secondPart);
        }
    }
}

BinaryReader逐字节或字符读取。 您将必须阅读每个字符,并尝试检查所需的组合。 如果找到“ B”,请检查next是否为“ R”,然后检查next是否为“ E”,依此类推。 可能还可以使用一些好的算法。

暂无
暂无

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

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