Title: Visual C Sharp File IO 1
1Visual C Sharp File I/O - 1
- Variables and arrays only temporary
- - lost when a program terminates
- Files used for long term storage
- (Data bases considered later in course)
- We will cover
- File types
- File and Directory classes
- File open and save dialogs
- Sequential-access files
- Random-access files
- Stream-input/output features
2Visual C Sharp File I/O - 2
- File Types Text (ASCII) or Binary
- Text files - ASCII characters with CR and LF.
- Handled in a line-by-line, or sequential manner.
- Binary Files - Typed and Untyped files
- Binary files all values - cant be displayed -
.EXE file. - Typed files - known format using data types -
database. Untyped files - no rigid structure,
sizes can vary. - E.g. EXE program files, BMP bitmap graphic files.
- - Program using it knows how to deal with it.
3Visual C Sharp File I/O - 3
- Files and streams
- C views files as a sequential stream of bytes.
- File ends with EOF marker or after a byte count.
- You open the file, read and write to it, then
close it. - Uses StreamReader and StreamWriter Classes
- They implement methods to read and write files.
- Similar classes used to read/write to Internet or
serial I/O
4Visual C Sharp File I/O - 4
- File and Directory Classes (static classes)
- Can perform Directory or File handling
- Directory
- CreateDirectory, Delete, GetFiles, Exists
- File
- Exists does file exist?
- Create creates file
- CreateText creates a text file
- AppendText appends or creates
- Delete deletes the file
- Open opens with desired R / W attributes
- OpenRead opens for read-only
- OpenText returns StreamReader (later)
- OpenWrite returns FileStream (later)
- Need using System.IO
5Visual C Sharp File I/O - 5
- First of all Menu and Dialog controls
- Text Editor example
- MenuStrip control used to create menus (File Edit
Help) - C has FileDialog controls open and save files
- OpenFileDialog SaveFileDialog
- Rich Text box control will display text files
- RT box has more functions than textbox cut,
paste etc.
6Visual C Sharp File I/O - 6
- File Dialog controls
- Open and Save dialogs
- non visual (not on form appear when program
runs) - ShowDialog displays the familiar open and save
dialogs
7Visual C Sharp File I/O - 7
- MenuStrip control
- Enter required main menu commands (File, Edit,
Help) - Add submenus FilegtOpen, Help gt About etc.
- To add code click File, double-click Open
- Add code
- if (openFileDialog1.ShowDialog( ) !
DialogResult.Cancel) -
- richTextBox1.LoadFile(openFileDialog1.FileName,
- RichTextBoxStreamType.PlainText)
- // more detail later
-
- ShowDialog method displays the familiar file
handling dialog
8Visual C Sharp File I/O - 8
- Code to display FileDialogs. Use
- openFileDialog1.ShowDialog( ) and
- saveFileDialog1.ShowDialog( )
- Need to check for OK or Cancel.
- if (openFileDialog1.ShowDialog( ) !
DialogResult.Cancel) -
- // filename is openFileDialog1.FileName
-
- N.b.
- File I/O needs namespace using System.IO
9Visual C Sharp File I/O - 9
- Open/Save File dialog properties
- CheckFileExists, DefaultExt InitialDirectory
etc. -
- File filter. Can set in code
- openFileDialog1.Filter "All files
(.).Text files(.TXT).txt"
10Visual C Sharp File I/O - 10
- Rich Text Box file handling
- Easiest way to open and save text files is to use
RTB - Open file
- if (openFileDialog1.ShowDialog() !
DialogResult.Cancel) -
- richTextBox1.LoadFile(openFileDialog1.FileName,
RichTextBoxStreamType.PlainText) -
- RTB has methods, e.g
- RTB.Find method finds strings in RTB (Search)
11Visual C Sharp File I/O - 11
- Rich Text Box file handling Save file
- For MenuStrip FilegtSave, add
- if (saveFileDialog1.ShowDialog( ) !
DialogResult.Cancel) -
- RichTextBox1.SaveFile(saveFileDialog1.FileNam
e, - RichTextBoxStreamType.PlainText)
-
- Text editor created in a few lines of code.
12Visual C Sharp File I/O - 12
- Using StreamReader to read file into RichTextBox
- StreamReader streamRdr new
StreamReader(openFileDialog1.FileName) - richTextBox1.Text streamRdr.ReadToEnd( )
- streamRdr.Close( )
- Writing file using StreamWriter
- StreamWriter streamWr new
- StreamWriter(saveFileDialog1.FileName)
- streamWr.Write(richTextBox1.Text)
- streamWr.Close( )
- Why use? may not want to use RT box to read file
13Visual C Sharp File I/O - 13
- Example code snippet read file
- string filename
- filename txtFilename.Text // read from textbox
- if ( File.Exists(filename) )
-
- string inputString File.ReadAllText(fileName)
- textBox1.Text inputString
-
14Visual C Sharp File I/O - 14
- Example code snippet - write
- string filename
- filename txtFilename.Text // read from textbox
- if ( File.Exists(filename) )
-
- File.WriteAllText(filename, txtFileName.txt)
- textBox1.Text inputString
-
15Visual C Sharp File I/O - 15
- Binary files
- // Read
- byte fileByteArray new byte1000
- fileByteArray File.ReadAllBytes("test.bin")
- // have to do something with the binary files to
display them - // could split into upper and lower nibbles and
add 40hex - // makes chars _at_ABC.. MNO
- // To Write
- File.WriteAllBytes("test.bin", fileByteArray)
16Visual C Sharp File I/O - 16
- Sequential-Access File Handling
- Non-text files? E.g. Student record (integer,
string, double) - Could create our own Record, Class, or even
object for this. - Search - Start at beginning and read data until
its found - Maybe necessary to do this lots of times
- How do we save Objects?
- Tell compiler our Class can be saved as bytes
Serializable attribute - FileStream class used to writing of binary data
- (instead of StreamReader/Writer)
17Visual C Sharp File I/O - 17
- Random Access File Handling
- Allows instant access to information
- - Individual records accessed without searching
through file - Easiest when all records are a fixed length
- Data can be inserted without destroying other
data in file - Records can be updated without rewriting the
entire file - Uses file-position pointer - points to next byte
to be read or written - can be repositioned to
any point in file - Uses class BinaryWriter and BinaryReader instead
of serialization - By attaching a FileStream to it, bytes can be
read/written directly to a file
18Visual C Sharp File I/O - 18
- Exception handling
- Exceptions File may not exist, divide by zero,
convert alpha string to number - Use Try .. Catch code
- int number1123, zero 0
- try
-
- number1 number1 / zero
-
- catch (DivideByZeroException)
-
- MessageBox.Show("Something's
wrong here") -
19Visual C Sharp File I/O - 19
- Summary
- File types
- File and Directory classes
- MenuStrip control
- Text Editor example RTBox
- Open / Save Dialogs
- Files and Streams
- Sequential-access files
- Random-access files