Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write data to a text file in C#?

Tags:

I can't figure out how to use FileStream to write data to a text file...

like image 336
lk5163 Avatar asked May 27 '11 13:05

lk5163


People also ask

How do you write to a file in C?

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.

How do you write a string of text into a file in C?

You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file.

How do you write the data into the files?

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.

Which command is used for write in file in C?

“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.


2 Answers

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)

like image 87
NickAldwin Avatar answered Sep 29 '22 11:09

NickAldwin


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"); 
like image 22
Yet Another Geek Avatar answered Sep 29 '22 11:09

Yet Another Geek