IST311 Chapter13.NET Files (Part2)

Similar documents
Console.ReadLine(); }//Main

Cleveland State University. Lecture Notes Feb Iteration Arrays ArrayLists. V. Matos

C# Data Manipulation

C# Data Manipulation

Recitation: Loop Jul 7, 2008

Files. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

CSIS 1624 CLASS TEST 6

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Files and Streams. Today you will learn. Files and Web Applications File System Information Reading and Writing with Streams Allowing File Uploads

RegEx - Numbers matching. Below is a sample code to find the existence of integers within a string.

To start we will be using visual studio Start a new C# windows form application project and name it motivational quotes viewer

RegEx-validate IP address. Defined below is the pattern for checking an IP address with value: String Pattern Explanation

1 EXTRACT TEXT FROM PDF USING THE PDF TOOLKIT WITH AQUAFOREST S OCR SDK SPLIT PDF MERGE PDF CREATE A PDF DOCUMENT...

Occupied versus Unoccupied

Chapter 14: Files and Streams

IST311 Chapter 8: C# Collections - Index-Sequential Search List & Dictionary PROGRAM

Problem Statement. B1: average speed

The contents of this document are directly taken from the EPiServer SDK. Please see the SDK for further technical information about EPiServer.

Lesson07-Arrays-Part4. Program class. namespace Lesson07ArraysPart4Prep { class Program { static double METER_TO_INCHES = 100 / 2.

Main Game Code. //ok honestly im not sure, if i guess its a class ment for this page called methodtimer that //either uses the timer or set to timer..

Lab 11. A sample of the class is:

emkt Browserless Coding For C#.Net and Excel

UNIVERSITY OF THE FREE STATE MAIN & QWA-QWA CAMPUS RIS 124 DEPARTMENT: COMPUTER SCIENCE AND INFORMATICS CONTACT NUMBER:

The Open Core Interface SDK has to be installed on your development computer. The SDK can be downloaded at:

Object oriented lab /second year / review/lecturer: yasmin maki

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

File Practice Problems

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Problem Statement. A1: being lapped on the track

// Program 2 - Extra Credit // CIS // Spring // Due: 3/11/2015. // By: Andrew L. Wright. //Edited by : Ben Spalding

J2ME .NET Compact Framework

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Computer Science And Engineering

Industrial Programming

// Precondition: None // Postcondition: The address' name has been set to the // specified value set;

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Threads & Networking

Lab - 1. Solution : 1. // Building a Simple Console Application. class HelloCsharp. static void Main() System.Console.WriteLine ("Hello from C#.

Here is a hierarchy of classes to deal with Input and Output streams.

File Handling Programming 1 C# Programming. Rob Miles

EEE-448 COMPUTER NETWORKS (Programming) Week -6 C# & IP Programming. The StringBuilder Class. StringBuilder Classes. StringBuilder with Append

Introduction to Java

How to read/write text file

A Summoner's Tale MonoGame Tutorial Series. Chapter 15. Saving Game State

Chapter 8 Files. File Streams

A Summoner's Tale MonoGame Tutorial Series. Chapter 8. Conversations

A sample print out is: is is -11 key entered was: w

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

You can call the project anything you like I will be calling this one project slide show.

Java file manipulations

Getting started with Java

Configuration Web Services for.net Framework

Principles, Models, and Applications for Distributed Systems M

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

BITG 1113: Files and Stream LECTURE 10

General Certificate of Education Advanced Subsidiary Examination June 2010

Principles, Models, and Applications for Distributed Systems M

Advanced Programming C# Lecture 2. dr inż. Małgorzata Janik

Learn C# Errata. 3-9 The Nullable Types The Assignment Operators

Introduction to C# Applications

Symphony G2 FDK API Manual for C# FDK API Manual for C# June ITS Company

class Class1 { /// <summary> /// The main entry point for the application. /// </summary>

Chapter 6: Files and Exceptions. COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016

Engr 123 Spring 2018 Notes on Visual Studio

CS 200 File Input and Output Jim Williams, PhD

create database ABCD use ABCD create table bolumler ( bolumkodu int primary key, bolumadi varchar(20) )

A1 Problem Statement Willie s Push-ups

API Guide MSS-8 and MVS-16

Using Template Bookmarks for Automating Microsoft Word Reports

2018/2/5 话费券企业客户接入文档 语雀

CALCULATOR APPLICATION

CHAPTER 1: INTRODUCING C# 3

Pace University. Fundamental Concepts of CS121 1

Input and Output File (Files and Stream )

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

University of Texas at Arlington, TX, USA

Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017

CS Week 11. Jim Williams, PhD

Windows File I/O. Files. Collections of related data stored on external storage media and assigned names so that they can be accessed later

This tutorial has been prepared for the beginners to help them understand basics of c# Programming.

*** TROUBLESHOOTING TIP ***

XNA 4.0 RPG Tutorials. Part 24. Level Editor Continued

Advanced Programming Methods. Lecture 9 - Generics, Collections and IO operations in C#

Brian Kiser November Vigilant C# 2.5. Commonwealth of Kentucky Frankfort, Kentucky

IT101. File Input and Output

Compile error. 2. A run time error occurs when the program runs and is caused by a number of reasons, such as dividing by zero.

UNIVERSITY OF THE FREE STATE DEPARTMENT OF COMPUTER SCIENCE AND INFORMATICS CSIS 2614 MODULE TEST 2

PES INSTITUTE OF TECHNOLOGY (BSC) V MCA, Second IA Test, September 2014

File I/O Array Basics For-each loop

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Annex B: Prototype Draft Model Code. April 30 th, 2015 Siamak Khaledi, Ankit Shah, Matthew Shoaf

OGSI.NET UVa Grid Computing Group. OGSI.NET Developer Tutorial

204111: Computer and Programming

PULSE - API. The purpose of this document is to provide example requests and responses for all relevant Pulse services requests

HTTPCOLONSLASHSLASHRJBDOTSOCDOTPORTDOTACDOTUKSLASHPUNKSLASH RIGHTRIGHTRIGHTRIGHTDOTZIP

Chapter 1 Getting Started


Chapter 8 Advanced GUI Features

About this exam review

COSC 6397 Big Data Analytics. Distributed File Systems (II) Edgar Gabriel Fall HDFS Basics

Transcription:

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; 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 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++) 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;

//RANDOMLY junk around the file Byte[] bytearray = new byte[40]; ; randomfile.seek(0, SeekOrigin.Begin); // seeking first record Console.WriteLine("First record is: \t" + Encoding.ASCII.GetString(byteArray) ); randomfile.seek(0, SeekOrigin.Begin); // seeking second record 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); 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 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 //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() List<LazyClsPerson> people = new List<LazyClsPerson>(); 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() 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() 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); // --------------------------------------------------------------------- StreamReader input = new StreamReader(@"c:\temp\mycsfile.txt"); string line; while ((line = input.readline())!= null) Console.WriteLine("ECHO>>> " + line); catch (Exception e) //Program Console.WriteLine("ERROR READING: " + e.message);