Documente Academic
Documente Profesional
Documente Cultură
Purpose of Files
serializable
File structures
Data Hierarchy:
Data Hierarchy
Sally
Black
Tom
Blue
Judy
Green
Iris
Orange
Randy
Red
Judy
Green
Judy
Field
01001010
1
bit
file
record
Note:
With sequential files,
individual records
can be of unequal
length. -
File class
C# Streams
2 major sets of stream classes
Byte streams read/write individual bytes
Corresponds to physical data network and
disk I/O streams
Low-level
C# programming example
File.CreateText method returns
a StreamWriter object.
StreamWriter fWriter =
File.CreateText("C:\\limerick.txt");
fWriter.WriteLine("That Computing is first about coding,");
fWriter.WriteLine("Is a thought that I find simply foreboding.");
fWriter.WriteLine("They should be taught instead");
fWriter.WriteLine("About using their head");
fWriter.WriteLine("or in ten years their careers will be folding");
fWriter.Close();
Points
StreamReader s = File.OpenText("c:\\limerick.txt");
do
{
Program
string line = s.ReadLine();
reads a line
if (line == null) break;
at a time
textBox1.Text += line;
and adds to
// Note, we could have used
a text box
// textBox1 += s.ReadToEnd();
textbox1 on
} while (true);
a form
textBox1.Text += "\n\n\n End";
}
catch (FileNotFoundException)
{
MessageBox.Show("Error", "Cannot find limerick.txt");
}
catch (IOException ie)
{
MessageBox.Show("Error", "IO exception");
}
Binary files
Binary files don't format data
This allows 'direct access' of a particular
record
Generally all records are of the same
length
Allows any object to be saved or read
back
Need to know the format to read it.
namespace SerialisableExample
{
public partial class Form1 : Form
{
int i = 0;
Person[] pList = new Person[100];
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string s = textBox1.Text;
Person p = new Person(s);
pList[i++] = p;
}
private void button2_Click(object sender, EventArgs e)
{
try
{
BinaryFormatter formatter
= new BinaryFormatter();
FileStream output = new FileStream("c:\\Person.dat", FileMode.
OpenOrCreate,
FileAccess.Write);
for (int j = 0; j < i; j++)
formatter.Serialize(output, pList[j]);
output.Close();
}
catch (SerializationException)
{
}
catch (FormatException)
{
}
}
Serializable Objects
Serialising an object