使用Stream writer将特定字节写入textfile

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

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

十六进制

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

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

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

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

这个例子将为您做到这一点:

 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 }); } 

使用hex编辑器打开“Bytes.data”文件时,您应该看到以下字节: 在此处输入图像描述

我只想出了这个。 它对我来说效果很好。 我们的想法是使用可以写入字节数组的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); 

如果我理解正确,您正在尝试将一些字符串写入文本文件,但您希望向此文件添加2个字节。

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

使用将字符串转换为Byte数组

 byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(str); // If your using UTF8 

从原始byteArray创建一个新的字节数组,并附加2个字节。

并使用以下方法将它们写入文件:

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

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

 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(); } 

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

保存字符串后,只需使用File.WriteAllBytes或BinaryWriter编写这些字节: 可以将Byte []数组写入C#中的文件吗?