If you intend to parse or convert the byte into its string equivalents, the StreamWriter should work fine as long as long as it does not need to be thread safe. For thread safety, look at TextWriter .
If you just want to write the byte to a file, look at FileStream class.
If you intend to parse the byte array into various types, consider using the BinaryWriter class.
For text file access i use StreamReader and StreamWriter objects. You can use them to write a new line for each packet of data as it is recieved:
public static void Main()
// Create an instance of StreamWriter to write text to a file.
// The using statement also closes the StreamWriter.
using (StreamWriter sw = new StreamWriter("TestFile.txt"))
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
Thanks for the reply. Got an idea to start with. I think I will need to use different methods on different occasions for convenience.
btw If I want to create the file (text file) in the current folder where my exe is running, how should I pass the file name argument in filestream instantiation?
I am relatively new to C# (Windows programming in general). I am basically a Microcontroller programmer who needs some windows application development skills.
Here is a method that uses the FileStream object, but you can also use the StreamWriter object to write data to a text file. The code below creates the file if it doesn't exist, then writes the data to the text file. If the file already exist you will use File.Append. Some of this code is from the Wrox 2005 C# book. Hope this helps.
public static void FileStreamOpenOrCreate(string path, char charData)
FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
byte byteData = new byte[charData.Length];
Encoder e = Encoding.UTF8.GetEncoder();
e.GetBytes(charData, 0, charData.Length, byteData, 0, true);
fs.Write(byteData, 0, byteData.Length);
If I want to create the file (text file) in the current folder where my exe is running, how should I pass the file name argument in filestream instantiation?
Hi Roy. If you pass in just the filename (no path), the file will be created in the same folder as where your application is running, which is the current working directory. The only caveat to this is, if your application's process changes the current working directory.