簡體   English   中英

使用Stream writer將特定字節寫入文本文件

[英]using Stream writer to Write a specific bytes to textfile

好吧,我正在嘗試向文本文件中寫入一些值和字符串。
但是此文本文件必須包含2個字節

這些是在將其他值寫入文本文件之后要插入到文本文件中的2個字節:

十六進制

我試過這種方法,但我不知道如何通過它寫字節

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

我不知道如何將它們放入所需的字符串后將它們寫入文本文件。

我只是想通了。 對我來說效果很好。 這個想法是用一個可以寫字節數組的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);

如果我從您的問題中正確記得。 您想將字符串寫入文件,然后將字節寫入文件嗎?

本示例將為您完成此操作:

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”文件時,應看到以下字節: 在此處輸入圖片說明

如果我理解正確,您正在嘗試向文本文件中寫入一些字符串,但是您想向該文件中添加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位值。 您應該能夠使用十六進制值(如char val = '\\xFFFE'設置變量並將其傳遞給Write 您還可以使用FileStream ,其中所有Write方法均以字節為單位,並且它專門具有WriteByte(byte)方法。 它的MSDN文檔提供了輸出UTF8文本的示例。

保存字符串后,只需使用File.WriteAllBytes或BinaryWriter等方式寫入這些字節:是否可以將Byte []數組寫入C#中的文件?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM