Reading and writing to text files had been made easy by .Net.
Following code will create a text file and insert 2 lines to it and will then read it and display.
- // System.IO is required for file handling.
- using System.IO;
- // Creating a stream writer object.
- // @ is used before the string to avoid the string getting broken by the /.
- StreamWriter stWriter = new StreamWriter(@"C:\Backup\File.txt");
- // Writing into the file.
- stWriter.Write("It is now ");
- stWriter.WriteLine(DateTime.Now);
- stWriter.WriteLine("The End");
- // Closing the file.
- stWriter.Close();
- // Reading the file.
- // Checking the availability of the file.
- if (File.Exists(@"C:\Backup\File.txt"))
- {
- // Without using the @, \\ also can be used to represent \ inside of a string.
- using (StreamReader stReader = File.OpenText("C:\\Backup\\File.txt"))
- {
- // Temporary variable.
- string str = "";
- while ((str = stReader.ReadLine()) != null)
- {
- // Assigning to a label.
- label1.Text += str + "\n";
- }
- }
- }
- else
- MessageBox.Show("Error, File cannot be found.");
No comments:
Post a Comment