File Input/Output (I/O) Tonga Institute of Higher Education
Working with Files and Directories Programs often work with files Changing files or directories Getting information about file or directory Getting data form a file or directory Saving data in a file or directory
System.IO Namespace The System.IO namespace contains many classes we can use to work with files and directories DirectoryInfo FileInfo StreamReader StreamWriter
Demonstration FileInfo
What is a Stream? Stream A stream is a sequence of data Streams are used to move data from one place to another In our computer: You can read from streams. Reading is the transfer of data from a stream into a data structure, such as a variable. You can write to streams. Writing is the transfer of data from a data structure, such as a variable, into a stream. Data Source Destination Stream
Writing and Reading Streams StreamReader – Object allows program to read data from a file using a stream. StreamWriter – Object allows program to write data to a file using a stream.
StreamReader Allows a program to read characters from a file Name of the file that will be read Loads 1 line Always close the file. Close releases any resources used by the system
StreamReader 2 The end of the file is reached when line is nothing
Demonstration StreamReader
StreamWriter Allows a program to write characters to a file Name of the file that will be written WriteLine includes a carriage return Close releases any resources used by the system
Demonstration StreamWriter
File Dialog Boxes Often, a user needs a GUI to select a file to open or enter the name and location of a file to save OpenDialogBox - Provides GUI for selecting a file to open SaveDialogBox - Provides GUI for inputting the name and location of a file to save
Open Dialog Box Provides GUI for selecting a file to open
Open Dialog Box GUI The properties can be set using the GUI There are many properties The properties can be set using the GUI
Open Dialog Box GUI Code But code must be used to display it and handle what the user does with it.
OpenFileDialog with GUI and Code Demonstration OpenFileDialog with GUI and Code
Using OpenFileDialog with Only Code Many developers prefer to create source code when using the OpenFileDialog box This allows the developer to see everything they have done
OpenFileDialog with Only Code Demonstration OpenFileDialog with Only Code