Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Stream writer to Write a specific bytes to textfile

Tags:

c#

text

stream

byte

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

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

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.

like image 492
user2799605 Avatar asked Oct 15 '13 21:10

user2799605


2 Answers

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();
}
like image 166
Rajesh Katare Avatar answered Sep 18 '22 15:09

Rajesh Katare


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.

Why won't you try using: 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 byteArray with the additional 2 bytes.

And write them to a file using:

File.WriteAllBytes("MyFile.dat", newByteArray)
like image 20
Yaniv Avatar answered Sep 20 '22 15:09

Yaniv