The following code example shows a simple way to write text to text files. Using system; using system.io;
class Test {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."); Sw.writeline ("---------- ------- "); // Arbitrary Objects Can Also Be Written to The File. SW.WRITE (" THE DATE IS: "); sw.writeLine (datetime.now);}}}
The following code example creates a new text file and writes a string. using System; using System.IO; public class TextToFile {private const string FILE_NAME = "MyFile.txt"; public static void Main (String [] args) {if (File.Exists (FILE_NAME)) {Console.WriteLine ( "{ 0} Already EXISTS. ", File_Name); Return;} streamwriter sr = file.createtext (file_name); Sr.Writeline (" this is my file. "); Sr.writeLine (" i can write intes {0} or floats {1}, and so on. ", 1, 4.2); Sr.close ();}} public static writtextfile (String logmessage) {if (logmessage! = Null && logmessage.length> 0) {system.io.streamwriter w = system.io.file.AppendText ("logserver.txt");
W.WriteLine ("Record Time: {0}", DateTime.now.toString ()); w.writeLine ("Information Text: {0}", LogMessage); w.writeline ("----- -------------------------------------------------- ---------------------------------- "); w.flush (); w.close () }}