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:
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.
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();
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With