C#在File.ReadAllBytes中跳过文件行?

时间:2018-06-26 14:07:08

标签: c# io byte

我只是想知道:我想在文件的第一行中以字符串形式插入版权声明,然后将二进制数据粘贴到它下面。 创建文件时我正在写通知。但是,如何强制File.WiteAllBytes方法在第0行之后开始并写入末尾?以及如何从第0行开始读取到文件结尾?

最好的问候!

K

2 个答案:

答案 0 :(得分:0)

我确实认为这是一个愚蠢的主意,在二进制文件的之前加上一些文本,因为那样的话,它就不再可用了。通常,版权文字会在文件的末尾附加,因为许多文件格式都可以抵抗这种类型的篡改(他们知道文件应具有的长度,而忽略了理论上的修改之后会发生什么情况)。文件)...但是您要求它:

// Write
string header = "Copyright © 2018 Foo Bar";
byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

string fileName = "hello.bin";

using (var fs = File.Create(fileName))
{
    byte[] bytes1 = Encoding.UTF8.GetBytes(header);
    byte[] bytes2 = new[] { (byte)'\r', (byte)'\n' };
    fs.Write(bytes1, 0, bytes1.Length);
    fs.Write(bytes2, 0, bytes2.Length);
    fs.Write(bytes, 0, bytes.Length);
}

// Read back
string header2;
byte[] byte2;

using (var fs = File.OpenRead(fileName))
{
    using (var ms = new MemoryStream())
    {
        int ch;
        while ((ch = fs.ReadByte()) != -1 && ch != '\n')
        {
            ms.WriteByte((byte)ch);
        }

        if (ms.Length > 0 && ms.GetBuffer()[ms.Length - 1] == '\r')
        {
            ms.SetLength(ms.Length - 1);
        }

        header2 = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
    }

    long length = fs.Length - fs.Position;

    byte2 = new byte[length];

    int ix = 0;

    // Technically the `fs.Read()` doesn't need to read the whole
    // buffer... it only needs to read one byte.
    while ((ix += fs.Read(byte2, ix, byte2.Length - ix)) < byte2.Length);
}

该标头是以UTF-8编写的(我正在使用它,请参见©中的header)。因此,我正在做一些捷径(如果您想在UTF-16中编写header,则需要进行一些更改)。

答案 1 :(得分:-2)

不能。没有允许使用的参数-请参见the documentation

您将必须阅读所有内容,添加注释并再次写出字节。