I have this snippet of code to write a file asynchronously:
private static async Task WriteTextAsync(string filePath, string text)
{ //Writes to our output files
byte[] encodedText = Encoding.UTF8.GetBytes(text);
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Create, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true))
{
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
};
}
The created text file is still ANSI format despite having set the Encoding.UTF8. There's 15 overloaded constructors for the FileStream class, and it's not obvious at all to me where I should set this if not on the encoded text.
I can tell the file is ANSI, because when I open it in TextPad and view the file statistics it lists ANSI as the Code Set:
Having problems, because MySQL LOAD INFILE is not reading the file properly, after reading the answers I believe it has something to do with the BOM, but not sure.
I tried this (for BOM):
byte[] encodedText = new byte[] { 0xEF, 0xBB, 0xBF }.Concat(Encoding.UTF8.GetBytes(text)).ToArray();
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Create, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true))
{
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
};
Textpad then saw it as UTF8, MySQL LOAD INFILE still failed. Resaved in Textpad, and MySQL saw it properly.
Changed code to this:
using (TextWriter writer = File.CreateText(filePath))
{
await writer.WriteAsync(text);
}
This seemed to work in both. I'm not sure what the issue is with MySQL LOAD INFILE regarding this.
No, it is definitely UTF-8:
byte[] encodedText = Encoding.UTF8.GetBytes(text);
That can only give you UTF-8; you then write encodedText to the stream.
However! UTF-8 will look identical to ASCII/ANSI for any characters in the 0-127 range. It only looks different above that. False positive?
I believe you forget to write BOM header to the beginning of the file. As you are using FileStream (and not some sort of TextWriter) you have to write it manually.
In case of UTF-8 it should be "EF BB BF"
Related
I have a file with size 10124, I am adding a byte array, which has length 4 in the beginning of the file.
After that the file size should become 10128, but as I write it to file, the size decreased to 22 bytes. I don't know where is the problem
public void AppendAllBytes(string path, byte[] bytes)
{
var encryptedFile = new FileStream(path, FileMode.Open, FileAccess.Read);
////argument-checking here.
Stream header = new MemoryStream(bytes);
var result = new MemoryStream();
header.CopyTo(result);
encryptedFile.CopyTo(result);
using (var writer = new StreamWriter(#"C:\\Users\\life.monkey\\Desktop\\B\\New folder (2)\\aaaaaaaaaaaaaaaaaaaaaaaaaaa.docx.aef"))
{
writer.Write(result);
}
}
How can I write bytes to the file?
The issue seems to be caused by:
using a StreamWriter to write binary formatted data. The name does not inthuitively suggest this, but the StreamWriter class is suited for writing textual data.
passing an entire stream instead of the actual binary data. To obtain the bytes stored in a MemoryStream, use its convenient ToArray() method.
I suggest you the following code:
public void AppendAllBytes(string path, byte[] bytes)
{
var fileName = #"C:\\Users\\life.monkey\\Desktop\\B\\New folder (2)\\aaaaaaaaaaaaaaaaaaaaaaaaaaa.docx.aef";
using (var encryptedFile = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var writer = new BinaryWriter(File.Open(fileName, FileMode.Append)))
using (var result = new MemoryStream())
{
encryptedFile.CopyTo(result);
result.Flush(); // ensure header is entirely written.
// write header directly, no need to put it in a memory stream
writer.Write(bytes);
writer.Flush(); // ensure the header is written to the result stream.
writer.Write(result.ToArray());
writer.Flush(); // ensure the encryptdFile is written to the result stream.
}
}
The code above uses the BinaryWriter class which is better suited for binary data. It has a Write(byte[] bytes) method overload that is used above to write an entire array to the file. The code uses regular calls to the Flush() method that some may consider not needed, but these guarantee in general, that all the data written prior the call of the Flush() method is persisted within the stream.
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.
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:
// StreamWriter writer = new StreamWriter(new FileStream("file.txt", FileMode.OpenOrCreate));
byte[] bytes = new byte[] { 0xff, 0xfe };
writer.BaseStream.Write(bytes, 0, bytes.Length);
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:
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)
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 FileStream where all the Write methods work off bytes, and it specifically has a WriteByte(byte) method. The MSDN documentation for it gives an example of outputting UTF8 text.
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#?
I am using following code to zip a file and it works fine but when I decompress with WinRar I get the original file name without the extension, any clue why if filename is myReport.xls when I decompress I get only myReport ?
using (var fs = new FileStream(fileName, FileMode.Open))
{
byte[] input = new byte[fs.Length];
fs.Read(input, 0, input.Length);
fs.Close();
using (var fsOutput = new FileStream(zipName, FileMode.Create, FileAccess.Write))
using(var zip = new GZipStream(fsOutput, CompressionMode.Compress))
{
zip.Write(input, 0, input.Length);
zip.Close();
fsOutput.Close();
}
}
GZip compresses only one file - without knowing the name. Therefore if you compress the file myReport.xls you should name it myReport.xls.gz. On decompression the last file extension will be removed so you end up with the original filename.
That its the way how it is used in Unix/Linux for ages...
Very weird indeed. A brief search came up with the following:
http://dotnetzip.codeplex.com/discussions/268293
Which says that GZipStream has no way of knowing the name of the stream that is being written, and suggests you set the FileName property directly.
Hope that helps.
I want to read an exe file in my C# code then decode as base64.
I am doing it like this
FileStream fr = new FileStream(#"c:\1.exe", FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader sr = new StreamReader(fr);
fr.Read(data, 0, count);
But the problem is that when I write this file the written file gets corrupted.
When analyzing in hex workshop code value 20 in hex is being replaced by 0.
A StreamReader should be used only with text files. With binary files you need to use directly a FileStream or:
byte[] buffer = File.ReadAllBytes(#"c:\1.exe");
string base64Encoded = Convert.ToBase64String(buffer);
// TODO: do something with the bas64 encoded string
buffer = Convert.FromBase64String(base64Encoded);
File.WriteAllBytes(#"c:\2.exe", buffer);
StreamReader official docs:
"Implements a TextReader that reads characters from a byte stream in a particular encoding."
It's for text, not binary files. Try just Stream or BinaryReader.. (Why did you try a StreamReader?)
CRM saves attachements in AnnotationBase base table.
How can I convert the text in the DocumentBody entity back to file and save it the file system.
I’m comfortable with plugins and workflow activities. But can't figure how to convert a string in the database to a file on the system.
using(FileStream fs = new FileStream("fileName", FileMode.Create,
FileAccess.Write))
{
StreamWriter writer = new StreamWriter(fs);
writer.Write(yourString);
fs.Flush();
}
[EDIT]
If we're talking about BASE64 strings then try this:
using (FileStream fs = new FileStream("fileName", FileMode.Create,
FileAccess.Write))
{
byte[] bytes = Convert.FromBase64String(yourString);
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
}
Grrr.
Look all day, then find the answer 5mins after posting the question.
File.WriteAllBytes("c:\\word1.docx", System.Convert.FromBase64String(str));