将字符串和字节写入同一个FileStream

时间:2015-04-07 21:22:08

标签: c# filestream streamwriter binarywriter

我需要创建一个文件,其中某些部分是字符串(utf-8),而某些部分是字节。

我使用StreamWriterBinaryWriter进行了数小时的修改,但这是唯一有效的方法:

        using (var stream = new FileStream(_caminho, FileMode.Create, FileAccess.Write))
        {
            using (var writer = new StreamWriter(stream))
            {
                writer.Write(myString);
            }   
        }
        using (var stream = new FileStream(_caminho, FileMode.Append, FileAccess.Write))
        {
            using (var writer = new BinaryWriter(stream))
            {
                writer.Write(oneSingleByte);
            }
        }

问题是我必须关闭FileStream并打开另一个只是为了写一个字节,因为BinaryStream.Write(string)方法预先设置"长度"字段(在我的情况下是不需要的)或StreamWriter.Write(byte)对字节值进行编码,而不是直接写入。

我的问题是:我可以使用另一个类,这样我只能创建一次FileStream,并一个接一个地写我的字符串和我的字节吗?

1 个答案:

答案 0 :(得分:3)

BinaryWriter为写入数据添加前缀,以便BinaryReader可以读取它。如果没有这些前缀,您必须确切地知道在编写和阅读文件时您正在做什么。

你可以省略两个作者并直接写入文件,如果这是你想要的:

using (var stream = new FileStream(_caminho, FileMode.Append, FileAccess.Write))
{
    stream.WriteByte('0'); 
    WriteString(stream, "foo", Encoding.UTF8);
}

private void WriteString(Stream stream, string stringToWrite, Encoding encoding)
{
    var charBuffer = encoding.GetBytes(stringToWrite);
    stream.Write(charBuffer, 0, charBuffer.Length);
}

您需要明确指定编码以获取字节,String.ToByteArray returns the string as Unicode characters,即.NET language for "UTF-16LE",每个字符为您提供两个字节。

相关问题