Files and Streams

37
Object Oriented Programming Files and Streams Files and Streams

description

C# Programing

Transcript of Files and Streams

  • Object Oriented Programming

    Files and Streams

  • ContentsIntroductionSequential file I/OClasses File and DirectorySerializationSummary

  • IntroductionMost applications require data to be stored in filesSpreadsheetsWord processingetcC# has an extensive set of classes for handling files of various typesThese are to be found in the System.IO namespaceAssociated with files is the general concept of streams which can be applied to both files and networks

  • IntroductionIn C#, streams are simply sequences of bytesNo formattng structure is placed on this byte stream, this is imposed by the applictionWe can read a byte stream from an input stream objectWe can write a byte stream to an output stream objectThe input and output stream objects are created from class FileStream

  • Introduction

  • Sequential file I/OThere are many classes in the FCL for file handlingFileStream is the basic file for handling I/O from binary filesThe constructor opens a stream object and specifies the filename and file access (read, write etc)It provides a Read() and Write() method Its normal to enclose file handling code in a try{} catch{} clause to catch any exceptions thrown

  • Sequential file I/Ousing System;using System.IO;class FileCopy{ public static void Main(String[] args){ try{ FileStream fromStream = new FileStream(args[0], FileMode.Open, FileAccess.Read); FileStream toStream = new FileStream(args[1], FileMode.Create, FileAccess.Write); Byte[] buffer = new Byte[fromStream.Length]; fromStream.Read(buffer, 0, buffer.Length); toStream.Write(buffer, 0, buffer.Length); }catch{ Console.WriteLine("Usage: FileCopy [FromFile] [ToFile]"); } }}

  • Sequential file I/OFileStream.Read() and FileStream.Write() are for binary filesData is stored in files as bytes which is efficient but not humanly readableA text file consists of information stored in humanly readable form For example the number 150 would be stored as 1 5 0 instead of the binary representation of 150 (10010110)C# has a number of classes (descended from the abstract TextReader and TextWriter classes) for handling text i/o

  • Sequential file I/OFor text files, classes StreamReader and StreamWriter are providedThese are derived from TextReader and TextWriterThey use the familiar ReadLine() and WriteLine() methods for doing formatted I/ONote that the Console class has StreamReader and StreamWriter objects and uses their ReadLine() and WriteLine() methods for doing console-based I/O

  • using System;using System.IO;

    class CreateTextFile{ public static void Main(String[] args) { try { FileStream toStream = new FileStream(args[0], FileMode.Create, FileAccess.Write); StreamWriter fileWriter = new StreamWriter(toStream);

    for (int i = 0; i < 10; i++) fileWriter.WriteLine("i= " + i);

    fileWriter.Close(); toStream.Close();

    FileStream fromStream = new FileStream(args[0], FileMode.Open, FileAccess.Read); StreamReader fileReader = new StreamReader(fromStream);

    for (int i = 0; i < 10; i++) { String input = fileReader.ReadLine(); Console.WriteLine(input); } } catch{Console.WriteLine("Usage: CreateTextFile OutputFile"); }}

  • Sequential file I/O

  • Classes File and Directory

    Classes File and Directory allow an application to obtain information about files and directories stored on discEach class contains a large set of static methods for both manipulation and information gatheringThese classes could be the basis of a hard disc scanning application to determine usage and the amount of available storage space

  • Classes File and Directory

    static Method

    Description

    AppendText

    Returns a StreamWriter that appends text to an existing file or creates a file if one does not exist.

    Copy

    Copies a file to a new file.

    Create

    Creates a file and returns its associated FileStream.

    CreateText

    Creates a text file and returns its associated StreamWriter.

    Delete

    Deletes the specified file.

    Exists

    Returns true if the specified file exists and false otherwise.

    GetCreationTime

    Returns a DateTime object representing when the file was created.

    GetLastAccessTime

    Returns a DateTime object representing when the file was last accessed.

  • Classes File and Directory

    static Method

    Description

    GetLastWriteTime

    Returns a DateTime object representing when the file was last modified.

    Move

    Moves the specified file to a specified location.

    Open

    Returns a FileStream associated with the specified file and equipped with the specified read/write permissions.

    OpenRead

    Returns a read-only FileStream associated with the specified file.

    OpenText

    Returns a StreamReader associated with the specified file.

    OpenWrite

    Returns a read/write FileStream associated with the specified file.

  • Classes File and Directory

    static Method

    Description

    CreateDirectory

    Creates a directory and returns its associated DirectoryInfo object.

    Delete

    Deletes the specified directory.

    Exists

    Returns true if the specified directory exists and false otherwise.

    GetDirectories

    Returns a string array containing the names of the subdirectories in the specified directory.

    GetFiles

    Returns a string array containing the names of the files in the specified directory.

    GetCreationTime

    Returns a DateTime object representing when the directory was created.

    GetLastAccessTime

    Returns a DateTime object representing when the directory was last accessed.

    GetLastWriteTime

    Returns a DateTime object representing when items were last written to the directory.

    Move

    Moves the specified directory to a specified location.

  • Classes File and DirectoryAs a simple example, we can use an OpenFileDialog box (which only allows files to be selected) or a FolderBrowserDialogWe can then use the File or Directory classes to print information about the selected itemFor a file we print the file size an d last modified dateFor a directory, we print its contents

  • using System;using System.Windows.Forms;using System.IO;

    public partial class FileTestForm1 : Form{ public FileTestForm1() { InitializeComponent(); }

    private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { string fileName = openFileDialog1.FileName; if (File.Exists(fileName)) displayFileInfo(fileName); }

    private void displayFileInfo(string fileName) {// Displays file information }

    private void displayDirectoryInfo(string pathName) {// Displays directory information }

    private void button1_Click(object sender, EventArgs e) {openFileDialog1.ShowDialog(); }

    private void button2_Click(object sender, EventArgs e) { folderBrowserDialog1.ShowDialog(); string pathName = folderBrowserDialog1.SelectedPath; if (Directory.Exists(pathName)) displayDirectoryInfo(pathName); }}

  • private void displayFileInfo(string fileName){ outputTextBox.Text += "\r\n\r\nFile: " + fileName + ":\r\n"; DateTime creationTime = File.GetCreationTime(fileName); outputTextBox.Text += "Created: " + creationTime.ToString() + "\r\n"; DateTime lastModifiedTime = File.GetLastAccessTime(fileName); outputTextBox.Text += "Last accessed: " + lastModifiedTime.ToString() + "\r\n";}

    private void displayDirectoryInfo(string pathName){ string[] directoryList; directoryList = Directory.GetDirectories(pathName); outputTextBox.Text += "\r\n\r\nDirectory Contents:\r\n";

    // Output directory contents for (int i = 0; i < directoryList.Length; i++)outputTextBox.Text += directoryList[i] + "\r\n";}Classes File and Directory

  • Demos\Files and Streams\FileTestForm.exeClasses File and Directory

  • SerializationIt is easy to write the individual fields of a record object to a fileFor example, we can create a record that stores information about a studentNameAddressID numberCourse enrolled foretcWe can output each field of this record to a file (either text or binary)

  • SerializationStudentInfoNameAddressID numberCourse InfoRecord filestring string int string

  • SerializationIn this example, any program that needs to read the file needs to know the format of the data2 strings, an int and then a stringAlso whether each item is on a separate lineObject serialization allows complete objects to be read or written with a single statementA serialized object is an object represented as a sequence of bytesInformation is stored about the data types of the objects instance fields as well as their valuesAllows the object to be reconstructed (de-serialized) from the file

  • SerializationStudentInfoNameAddressID numberCourse InfoRecord fileStudentInfo object

  • SerializationTo serialize an object, the object class needs to be marked with the [Serializable] attribute or needs to implement the ISerializable interfaceRequires the System.Runtime.Serialization namespaceAlso we require a BinaryFormatter object to serialize/de-serialize the object before writing to or reading from fileIts also possible to serialize objects using SOAP (simple object access protocol) or XML using the appropriate formatters

  • SerializationExample. A custom serializer GUI

  • SerializationThe user inputs student info. details in the corresponding textboxes on the left which through the serialization will be stored in a binary fileThe information in the binary file will be deserialized and displayed in the right hand textboxesWe will create a simple StudentInfo class and tag it as Serializable

  • Serialization[Serializable]class StudentInfo{ public string Name, Address, CourseInfo; public int ID;

    public StudentInfo() {}

    public StudentInfo(String n, String a, String ci, int id) { Name = n; Address = a; CourseInfo = ci; ID = id; }}

  • using System.Windows.Forms;using System.IO;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;

    public partial class SerializerTestForm1 : Form{ private String fileName = Directory.GetCurrentDirectory() + "\\output1.txt"; public SerializerTestForm1() { InitializeComponent(); }

    private void button1_Click(object sender, EventArgs e) { //Serialize textbox data so a binary file }

    private void button2_Click(object sender, EventArgs e) { //Serialize textbox data so a binary file }}Serialization

  • Serializationprivate void button1_Click(object sender, EventArgs e){ button1.Enabled = false; String name = textBox1.Text; String address = textBox2.Text; int id = Convert.ToInt32(textBox3.Text); String courseInfo = textBox4.Text; StudentInfo s = new StudentInfo(name,address,courseInfo,id);

    FileStream filestream = new FileStream(fileName, FileMode.Create); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(filestream, s); filestream.Close(); button1.Enabled = true;}

    private void button2_Click(object sender, EventArgs e){ FileStream filestream2 = new FileStream(fileName,FileMode.Open); BinaryFormatter bf2 = new BinaryFormatter(); StudentInfo si= new StudentInfo(); si = (StudentInfo)bf2.Deserialize(filestream2); textBox8.Text = si.Name; textBox7.Text = si.Address; textBox6.Text = ""+si.ID; textBox5.Text = si.CourseInfo; filestream2.Close();}

  • Serialization

    Demos\Files and Streams\SerializerTestForm.exe

  • Serialization

  • SerializationBinary serialization is limited as only .NET applications can deserialize the data streamFor more general inter-operability especially across a network, XML serialization is usedXML is text based and self describing and universalComprised name/attribute pairsXML serialization easy to implement and uses text streams

  • SerializationWe need to insert XML tags into our StudentInfo classOnly public properties and fields can be serialized[XmlRoot("studentInfo")]public class StudentInfo{ [XmlAttribute("name")] public string Name; [XmlAttribute("address")] public string Address; [XmlAttribute("course")] public string CourseInfo; [XmlAttribute("id")] public int ID; public StudentInfo() { }

    public StudentInfo(String n, String a, String ci, int id) { Name = n; Address = a; CourseInfo = ci; ID = id; }}

  • using System;using System.Windows.Forms;using System.IO;using System.Xml;using System.Xml.Serialization;

    public partial class xmlSerializerTestForm1 : Form{ private String fileName = Directory.GetCurrentDirectory() + "\\output1.xml"; public xmlSerializerTestForm1() {InitializeComponent();} private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; String name = textBox1.Text; String address = textBox2.Text; int id = Convert.ToInt32(textBox3.Text); String courseInfo = textBox4.Text; StudentInfo si = new StudentInfo(name, address, courseInfo, id); XmlSerializer xmls = new XmlSerializer(typeof(StudentInfo)); TextWriter w = new StreamWriter(fileName); xmls.Serialize(w, si); w.Close(); button1.Enabled = true; }

    private void button2_Click(object sender, EventArgs e) { StudentInfo si; XmlSerializer xmls = new XmlSerializer(typeof(StudentInfo)); TextReader r = new StreamReader(fileName); si = (StudentInfo)xmls.Deserialize(r); textBox8.Text = si.Name; textBox7.Text = si.Address; textBox6.Text = "" + si.ID; textBox5.Text = si.CourseInfo; r.Close(); }}

  • Serialization

  • SummaryWe have seen how we can use streams to do simple sequential file I/O for binary and text filesWe have looked at how we can use the File and Directory classesWe have looked at object serialization to binary and XML