IST311 – Chapter13 – .NET Files (Part2)

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.IO;

using System.Linq;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading.Tasks;

using System.Xml;

using System.Xml.Serialization;

namespace Draft13

{

class Program

{

static void Main(string[] args)

{

//Experiment01(); // reading & writing text files

//Experiment02(); // reading & interpreting data

//Experiment03(); // serializing XML data

//Experiment04(); // serialize a list of person objects

//Experiment05(); // de-serialize a list of Person objects

//Experiment06(); // merge two files

//Experiment07(); // Problem 13.01

//Experiment08(); // the using(...){} clasuse

//Experiment10(); // convert byte[] <-> string

//Experiment11(); // files - random access mode

Console.ReadLine();

}//Main /////////////////////////////////////////////////////////////////////

private static void Experiment10()

{

// converting char[], byte[], string

char[] charArray = new char[] { 'H', 'E', 'L', 'L', 'O' };

string strValue = new string(charArray);

Console.WriteLine(strValue.Length + " " + strValue);

char[] charArray2 = "Hello world".ToCharArray();

string strValue2 = new string(charArray2);

Console.WriteLine( strValue2.Length + " " + strValue2);

string str = "123".PadRight(20);

Console.WriteLine( str.Length + "***" + str + "***");

byte[] byteArray = Encoding.ASCII.GetBytes("Hola mundo");

string strFromBytes = Encoding.ASCII.GetString(byteArray);

Console.WriteLine( byteArray );

Console.WriteLine( strFromBytes);

}

// ////////////////////////////////////////////////////////////////////////////////////////

private static void Experiment11()

{

//PART1. Craete the random file.

FileStream randomFile = null;

try

{

randomFile = new FileStream(@"c:\temp\randomDatFile.dat", FileMode.Create);

Console.WriteLine("Done with random file");

}

catch (IOException e)

{

Console.WriteLine("error " + e.Message);

return;

}

finally

{

randomFile.Close();

}

//PART2. reopen the file, add records

try

{

randomFile = new FileStream(@"c:\temp\randomDatFile.dat", FileMode.Open);

}

catch (Exception e)

{

Console.WriteLine("ERROR " + e.Message);

}

// Write ten RECORDS. Each record consists of 40 chars, begins with a key (3digits)

// then some data, last symbol is "0".

for (int i = 0; i < 10; i++)

{

try

{

String strRec = ((100 + i)

+ " rest of the data record goes here").PadRight(39) + "0";

randomFile.Write(Encoding.ASCII.GetBytes(strRec), 0, 40);

}

catch (IOException exc)

{

Console.WriteLine(exc.Message);

return;

}

}

try

{

//RANDOMLY junk around the file

Byte[] byteArray = new byte[40]; ;

randomFile.Seek(0, SeekOrigin.Begin); // seeking first record

randomFile.Read(byteArray, 0, 40);

Console.WriteLine("First record is: \t" + Encoding.ASCII.GetString(byteArray) );

randomFile.Seek(0, SeekOrigin.Begin); // seeking second record

randomFile.Read(byteArray, 0, 40);

Console.WriteLine("Second record is: \t" + Encoding.ASCII.GetString(byteArray));

//traverse the random file

int offset;

for (int i = 0; i < 10; i++)

//for(int i=9; i>= 0; i--)

//for(int i=0; i< 10; i+=2)

{

offset = 40 * i;

randomFile.Seek(offset, SeekOrigin.Begin);

randomFile.Read(byteArray, 0, 40);

Console.WriteLine("Record at location {0} is \t {1}" ,

i, Encoding.ASCII.GetString(byteArray));

}

//apply a 'logical delete' to a record at given position

int posRecordToDelete = 7;

offset = 40 * posRecordToDelete;

randomFile.Seek(offset, SeekOrigin.Begin); // seeking record

randomFile.Read(byteArray, 0, 40);

Console.WriteLine("Before deleting \t" + Encoding.ASCII.GetString(byteArray));

byteArray[39] = (byte)'1'; //change last byte

Console.WriteLine("After marking \t" + Encoding.ASCII.GetString(byteArray));

randomFile.Seek(offset, SeekOrigin.Begin); // seeking record

randomFile.Write(byteArray, 0, 40); //write changed record back to disk

randomFile.Seek(offset, SeekOrigin.Begin); // seeking record

randomFile.Read(byteArray, 0, 40); //read record

Console.WriteLine( "After deleting \t" + Encoding.ASCII.GetString(byteArray) );

Console.WriteLine();

}

catch (IOException exc)

{

Console.WriteLine(exc.Message);

}

Console.WriteLine();

randomFile.Close();

}

private static void Experiment07()

{

//Exmaples:

//DirectoryInfo info = new DirectoryInfo(".");

//DirectoryInfo info = new DirectoryInfo(@"c:/temp");

DirectoryInfo info = new DirectoryInfo(@"c:/");

// ------

// find all files in given directory

string result = info.FullName + "\n\n"

+ "File Names".PadRight(40)

+ "Size".PadLeft(20) + "\n";

foreach (FileInfo myfile in info.GetFiles("*.*"))

{

result += myfile.Name.PadRight(40) + myfile.Length.ToString().PadLeft(20) + "\n";

}

Console.WriteLine(result);

// list all sub-directories under given folder

foreach (DirectoryInfo myDir in info.GetDirectories())

{

result += "DIR... " + myDir.Name + "\n";

}

Console.WriteLine(result);

//look for a particular file, make a copy, finally delete the original

if (File.Exists(@"c:/temp/mergedfile.txt"))

{

File.Copy(@"c:/temp/mergedfile.txt", @"c:/temp/mergedfile_copy.txt");

File.Delete(@"c:/temp/mergedfile.txt");

Console.WriteLine(@"Done with copy-delete see mergedfile_copy.txt");

}

}

private static void Experiment06()

{

//merge two files put results in a new file

StreamReader infile1 = new StreamReader(@"c:/temp/mergingfile1.txt");

StreamReader infile2 = new StreamReader(@"c:/temp/mergingfile2.txt");

StreamWriter outfile = new StreamWriter(@"c:/temp/mergedfile.txt");

string line1 = infile1.ReadLine();

string line2 = infile2.ReadLine();

while (line1 != null & line2 != null)

{

if (line1.CompareTo(line2) <= 0)

{

outfile.WriteLine(line1);

line1 = infile1.ReadLine();

}

else

{

outfile.WriteLine(line2);

line2 = infile2.ReadLine();

}

}

while (line1 != null)

{

outfile.WriteLine(line1);

line1 = infile1.ReadLine();

}

while (line2 != null)

{

outfile.WriteLine(line2);

line2 = infile2.ReadLine();

}

infile1.Close();

infile2.Close();

outfile.Close();

Console.WriteLine("Merging done...");

}

private static void Experiment05()

{

XmlDocument doc = new XmlDocument();

doc.Load(@"c:/temp/mycsfile3.xml");

foreach (XmlNode node in doc.DocumentElement.ChildNodes)

{

string text = node.InnerText; //or loop through its children as wel

Console.WriteLine(text);

}

foreach (XmlNode node in doc.DocumentElement.SelectNodes("LazyClsPerson/FirstName"))

{

string text = node.InnerText; //or loop through its children as wel

Console.WriteLine(text);

}

foreach (XmlNode node in doc.DocumentElement.SelectNodes("LazyClsPerson/Phone"))

{

string text = node.InnerText; //or loop through its children as wel

Console.WriteLine(text);

}

Console.WriteLine("Done Experiment05");

}

private static void Experiment04()

{

ListLazyClsPerson> people = new ListLazyClsPerson>();

LazyClsPerson person1 = new LazyClsPerson();

person1.FirstName = "Sansa";

person1.LastName = "Stark";

person1.Phone = "555-7777";

LazyClsPerson person2 = new LazyClsPerson();

person2.FirstName = "Arya";

person2.LastName = "Stark";

person2.Phone = "555-6666";

people.Add(person1);

people.Add(person2);

//XmlSerializer xmlSerializer =

// new XmlSerializer(people.GetType());

//xmlSerializer.Serialize(Console.Out, people);

//Console.WriteLine();

//Console.ReadLine();

XmlSerializer xmlSerializer = new XmlSerializer(people.GetType());

StreamWriter outputfile = new StreamWriter(@"c:/temp/mycsfile3.xml");

xmlSerializer.Serialize(outputfile, people);

Console.WriteLine("Done Experiment04");

Console.ReadLine();

}

private static void Experiment03()

{

LazyClsPerson person = new LazyClsPerson();

person.FirstName = "Sansa";

person.LastName = "Stark";

person.Phone = "555-7777";

XmlSerializer xmlSerializer =

new XmlSerializer(person.GetType());

xmlSerializer.Serialize(Console.Out, person);

Console.WriteLine();

Console.ReadLine();

}

private static void Experiment02()

{

try

{

StreamReader infile = new StreamReader(@"c:/temp/mycsfile2.txt");

String line;

int row = 0;

string[] tokens = new string[3]; //first, last, phone

while ((line = infile.ReadLine()) != null)

{

string[] dataChunk = line.Split();

if (dataChunk.Length == 3)

tokens = dataChunk;

if (dataChunk.Length == 2)

{

tokens[0] = dataChunk[0];

tokens[1] = ""; //no last name!

tokens[2] = dataChunk[1];

}

for (int i = 0; i < tokens.Length; i++)

{

Console.WriteLine(row + "\t" + i + "\t" + tokens[i]);

}

Console.WriteLine();

row++;

}

}

catch (Exception e)

{

Console.WriteLine("PROBLEM: " + e.Message);

Environment.Exit(0);

}

}

private static void Experiment01()

{

try

{

StreamWriter output = new StreamWriter(@"c:/temp/mycsfile.txt");

for (int i = 0; i < 5; i++)

{

output.WriteLine("this is line-" + i);

}

output.WriteLine(DateTime.Now);

output.Close();

}

catch (Exception e)

{

Console.WriteLine("ERROR: " + e.Message);

}

// ------

try

{

StreamReader input = new StreamReader(@"c:\temp\mycsfile.txt");

string line;

while ((line = input.ReadLine()) != null)

{

Console.WriteLine("ECHO> " + line);

}

}

catch (Exception e)

{

Console.WriteLine("ERROR READING: " + e.Message);

}

}

}//Program

}