使用Stream writer将特定字节写入文本文件

时间:2013-10-15 21:06:15

标签: c# text stream byte

我正在尝试将一些值和字符串写入文本文件 但是这个文本文件必须包含2个字节

在完成向其写入其他值后,我想要插入到文本文件中的2个字节:

hex

我试过这个方法,但我不知道如何通过它写字节

using (StreamWriter sw = new StreamWriter(outputFilePath, false, Encoding.UTF8))

我不知道如何在把我想要的字符串放到文本文件后把它们写到文本文件中。

6 个答案:

答案 0 :(得分:15)

我只想出了这个。它对我很有用。我们的想法是使用可以写入字节数组的FileStream打开文件,并在其上面放置StreamWriter来编写字符串。然后你可以使用两者来混合字符串:

// StreamWriter writer = new StreamWriter(new FileStream("file.txt", FileMode.OpenOrCreate));

byte[] bytes = new byte[] { 0xff, 0xfe };
writer.BaseStream.Write(bytes, 0, bytes.Length);

答案 1 :(得分:9)

如果我从你的问题中回忆正确的话。您想将字符串写入文件然后将字节写入其中吗?

此示例将为您执行此操作:

using (FileStream fsStream = new FileStream("Bytes.data", FileMode.Create))
using (BinaryWriter writer = new BinaryWriter(fsStream, Encoding.UTF8))
{
    // Writing the strings.
    writer.Write("The");
    writer.Write(" strings");
    writer.Write(" I");
    writer.Write(" want");
    writer.Write(".");

    // Writing your bytes afterwards.
    writer.Write(new byte[]
                 {
                     0xff,
                     0xfe
                 });
}

使用十六进制编辑器打开“Bytes.data”文件时,您应该看到以下字节: enter image description here

答案 2 :(得分:3)

如果我理解正确,你试图将一些字符串写入文本文件,但是你想在这个文件中添加2个字节。

为什么不尝试使用:File.WriteAllBytes?

使用

将字符串转换为字节数组
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(str); // If your using UTF8

使用额外的2个字节从原始的 byteArray 创建一个新的字节数组。

使用以下命令将它们写入文件:

File.WriteAllBytes("MyFile.dat", newByteArray)

答案 3 :(得分:1)

这是寻找解决方案的另一种方法......

StringBuilder sb = new StringBuilder();

sb.Append("Hello!! ").Append(",");
sb.Append("My").Append(",");
sb.Append("name").Append(",");
sb.Append("is").Append(",");
sb.Append("Rajesh");
sb.AppendLine();

//use UTF8Encoding(true) if you want to use Byte Order Mark (BOM)
UTF8Encoding utf8withNoBOM = new UTF8Encoding(false);

byte[] bytearray;

bytearray = utf8withNoBOM.GetBytes(sb.ToString());

using (FileStream fileStream = new FileStream(System.Web.HttpContext.Current.Request.MapPath("~/" + "MyFileName.csv"), FileMode.Append, FileAccess.Write))
{
    StreamWriter sw = new StreamWriter(fileStream, utf8withNoBOM);

    //StreamWriter for writing bytestream array to file document
    sw.BaseStream.Write(bytearray, 0, bytearray.Length);
    sw.Flush();
    sw.Close();

    fileStream.Close();
}

答案 4 :(得分:0)

StreamWriter.Write(char)将写入16位值。您应该能够使用像char val = '\xFFFE'这样的十六进制值设置变量,并将其传递给Write。您还可以使用FileStream,其中所有Write方法都可以在字节之外工作,并且它具体使用WriteByte(byte)方法。 MSDN documentation为它提供了输出UTF8文本的示例。

答案 5 :(得分:-1)

保存字符串后,只需使用File.WriteAllBytes或BinaryWriter编写这些字节: Can a Byte[] Array be written to a file in C#?

相关问题