I'm having trouble figuring out how to switch between StreamWriter to write out text and FileStream to dump a byte[] into a file.
I'm using StreamWriter to manually write out an XML in text (there are reasons I'm not using XMLWriter). In two sections, a byte[] array needs to be dumped into the file (TIF image). I know if can somehow be done because I'm trying to mimic a file we get from our vendor. I was trying to just use the StreamWriter and convert the byte[] to a string using ISO-8859-1, but there are some additional characters that get put it that make it an invalid TIF.
Am I overthinking this? Do I need to close the StreamWriter, reopen the file and append using the FileStream, the close and reopen with StreamWriter to write additional text?
edit: OK, this almost works. The binary portion is now fine, but all of the text portion has 0x00 in between each character.
using (System.IO.FileStream fileST = new System.IO.FileStream(filenameST, FileMode.Create, FileAccess.Write))
{
string z;
fileST.Write(Encoding.Unicode.GetBytes(z =""), 0, z.Length);
fileST.Write(Encoding.Unicode.GetBytes(z =partID), 0, z.Length);
fileST.Write(Encoding.Unicode.GetBytes(z ="Content-Type: text/xml; charset=UTF-8"), 0, z.Length);
fileST.Write(Encoding.Unicode.GetBytes(z ="Content-Transfer-Encoding: binary"), 0, z.Length);
fileST.Write(Encoding.Unicode.GetBytes(z ="Content-Id: <" + contentID + ">"), 0, z.Length);
fileST.Write(Encoding.Unicode.GetBytes(z =""), 0, z.Length);
//truncated
fileST.Write(Encoding.Unicode.GetBytes(z =imagekey + "00FBW"), 0, z.Length);// + System.Convert.ToBase64String(Miscellaneous.MiscTools.GEncheckImageFront(outputPath, font)), 0, z.Length);
fileST.Write(aFrontImage, 0, aFrontImage.Length);
}
Where aFrontImage is the byte[] of the tif file.
The original code was:
using (System.IO.StreamWriter fileST = new System.IO.StreamWriter(filenameST))
{
string partID = "------=_Part_" + partline1 + "_" + partline2 + ".0" + XMLdata[i, 0].GetLast(4) + XMLdata[i, 3].GetLast(5) + "321";
string contentID = Guid.NewGuid().ToString().Replace("-", "").ToUpper();
fileST.WriteLine("");
fileST.WriteLine(partID);
fileST.WriteLine("Content-Type: text/xml; charset=UTF-8");
fileST.WriteLine("Content-Transfer-Encoding: binary");
fileST.WriteLine("Content-Id: <" + contentID + ">");
fileST.WriteLine("");
Just convert your string and write all bytes to the file. Depending on your encoding you can do something like this:
bytes[] stringAsBytes = Encoding.Unicode.GetBytes(myString)