Text Files

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

Text files store information as Unicode characters within a basic file readable by any text editor. Unlike Binary Files, text files can only store information as a string. If you wish to retrieve an integer or Boolean variable from a file, it must be converted.

https://www.youtube.com/watch?v=HQ--D7GTsbs&index=3&list=PLCiOXwirraUD0G290WrVKpVYd3leGRRMW

Reading and writing data to text files

Within C# you can write information to a text file using the Streamwriter or streamreader class.Below are some examples on how to do this. The relative path is the path to the file you wish to access.

Example of writing data to a text file

When writing to a text file that does not exist, the file will be created, however, any non-existent folders specified within the path will not be created.

 1 class Program 
 2 {
 3     static void Main(string[] args)
 4     {
 5        using (StreamWriter ExampleName = new Streamwriter("Relative/path/example.txt"))
 6        {
 7            //from this point, the streamwriter can be treated like you are outputting data to the screen via console.write commands
 8            ExampleName.Write("Hello World");
 9            ExampleName.Writeline("Writeline also works");
10        }
11     }
12 }

Example of reading data from a text file

Reading information works much the same way with StreamReader instead of StreamWriter

 1 class Program 
 2 {
 3     static void Main(string[] args)
 4     {
 5        using (StreamReader ExampleName = new StreamReader("Relative/path/example.txt"))
 6        {
 7            //when reading information from text files you can treat it much the same as when you read input from the console. e.g
 8            //This example reads the next character from the file and stores it in the string 'Example1'
 9            string Example1 = ExampleName.Read();
10            //This example reads a line of data from the text file and stores it in the string 'Example2'
11            string Example2 = ExampleName.ReadLine();
12            //This Example reads the entire file, and stores it in the variable 'Example3'
13            string Example3 = ExampleName.ReadToEnd();
14            //If some data is supposed to be interpreted as a different variable type to string, it must be converted like this
15            //This Example reads the next line of an input file and converts the output into an integer for storage in the respective variable
16            int Example4 = Convert.ToInt32(ExampleName.ReadLine());
17        }
18     }
19 }