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

时间:2013-06-06 03:40:11

标签: c# filestream binaryreader

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

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

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

我想从 0到'BREAK'之前和'BREAK'之后阅读C#中的文件结尾。请帮帮我。

2 个答案:

答案 0 :(得分:1)

BinaryWriter用于编写非人类可读格式,因此二进制。例如,如果要编写基元类型you can just write them in their byte representation (like 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);
        }
    }
}

答案 1 :(得分:0)

BinaryReader逐字节或字符读取。您必须阅读每个字符并尝试检查您正在寻找的组合。如果找到“B”,如果是,则检查next是否为“R”,然后检查next是否为“E”,依此类推。可能还有一些好的算法可供选择。