C# 使用流编写器将特定字节写入文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19391073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:53:00  来源:igfitidea点击:

using Stream writer to Write a specific bytes to textfile

c#textstreambyte

提问by user2799605

Well I'm trying to write some values and strings to a text file.
but this text file must contain 2 bytes

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

These are the 2 bytes I want to insert to my text file after finishing writing the other values to it:

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

hex

十六进制

I tried this method but I have no idea how to write bytes through it

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

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

I have no idea about how to write them to the text file after putting the strings I want on it.

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

采纳答案by Measuring

If I recall correctly from your question. You want to write strings to a file and then write bytes to it?

如果我从你的问题中没有记错的话。您想将字符串写入文件,然后向其中写入字节吗?

This example will do that for you:

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

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

When opening the "Bytes.data" file with a hex editor you should see these bytes: enter image description here

使用十六进制编辑器打开“Bytes.data”文件时,您应该看到以下字节: 在此处输入图片说明

回答by Pellared

After saving the string simply write those bytes using for example using File.WriteAllBytes or a BinaryWriter: Can a Byte[] Array be written to a file in C#?

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

回答by jltrem

There is a StreamWriter.Write(char)that will write a 16-bit value. You should be able to set your variable with the hex value like char val = '\xFFFE'and pass it to Write. You could also use FileStreamwhere all the Write methods work off bytes, and it specifically has a WriteByte(byte)method. The MSDN documentationfor it gives an example of outputting UTF8 text.

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

回答by Yaniv

If I understand correctly, you're trying to write some strings to a text file, but you want to add 2 bytes to this file.

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

Why won't you try using: File.WriteAllBytes ?

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

Convert your string to a Byte array using

使用将您的字符串转换为字节数组

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

Create a new byte array from the original byteArraywith the additional 2 bytes.

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

And write them to a file using:

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

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

回答by Bitterblue

I just figured this out. It works quite well for me. The idea is you open the file with a FileStream that can write byte arrays, and put a StreamWriter on top of it to write strings. And then you can use both to mix strings with your bytes:

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

回答by Rajesh Katare

Here is one more way to look for a solution...

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

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