I can't figure out how to use FileStream to write data to a text file...
For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the file versions of printf() and scanf() . The only difference is that fprintf() and fscanf() expects a pointer to the structure FILE.
You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file.
Data is written to a file using the PRINTF statement. The statement may include the FORMAT keyword to control the specific structure of the written file. Format rules are needed when writing an array to a file. Writing data to a file using simple format rules in the PRINTF procedure.
“wb” – Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
Assuming you have the data already:
string path = @"C:\temp\file"; // path to file using (FileStream fs = File.Create(path)) { // writing data in string string dataasstring = "data"; //your data byte[] info = new UTF8Encoding(true).GetBytes(dataasstring); fs.Write(info, 0, info.Length); // writing data in bytes already byte[] data = new byte[] { 0x0 }; fs.Write(data, 0, data.Length); }
(taken from msdn docs and modified)
The documentation for FileStream gives an excellent example. In short you create a filestream object, and use the Encoding.UTF8 object (or the encoding you want to use) to convert your plaintext to bytes, in which you can use your filestream.write method. But it would be easier to just use the File class, and File.Append* methods.
EDIT: Example
File.AppendAllText("/path/to/file", "content here");
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