Tải bản đầy đủ (.pdf) (142 trang)

Ebook lập trình c từ cơ bản đến nâng cao phần 2 phạm công ngô

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.07 MB, 142 trang )

ChươNq 8 . F ì I es
Khi cần lưii dữ liệu vào đĩa,
cung cấp một cơ chế để thite hiện
giống như mọi ngôn ngữ khác. Có hai cách ghi và đọc dử liệu vào íiles;
kiểu file íext và kiểu file nhị phân.
8. 1 . G

H I/Đ Ọ C

F IL E T E X T

using System.10;

8.1.1. Ghi d ữ liệu v ã o file
Cú pháp để ghi dữ liệu vào íile:
s t r in g filenaine = ” c ; \ \ C S \ \ t e s t ĩ . t x t
StreamWriter sw = new StreamVỉriter (filename)
sw.Write("This i s the t e x t ." ) ;

Sau khi ghi xong cần phải đóng file lại.
sw.Close () ;

8.1.2. Đ ọ c dO liệu tù file
s t r in g filenaiTte “ " c : \ \ c s \ \ t e s t l . txt" ;



StreamReader s r l = new StreamReader {filenam e);
srl.R eadL ine 0 ;
s r l.C lo s e O ;



^ViàụS.l.
using System;
using System.10;
using System.Text;
c ia s s PileText
s t a t i c str in g f i l e l * * ' c : \ \ t e s t f i l e . t x t . ” ;
s t a t i c doxible a * 123.456;
• s t a t ic in t b * 789;
s t a t i c châr kt *

1 01


s t a t i c void Main(stríng( ] args)

{
using (StreamVỉriter sw = new StreêưnWriter ( f i l e l ) )

{
sw.Write {•'This i s a te x t; a “ ");
sw.W riteLine(â);
sw.WriteLine (b);
sví.VíriteLine (k t);
sw.Close ();
ì
StreamReader s r l " new Stream R eađ er(filel);
s t r in g input;
w h ile ((in p u t = srl.R eadL ine( ) ) ! = null)
Consoĩe.W riteLine(input);


)
Console.WriteLine("Ket th u c!")!
s r l.C io s e ();
Console. ReađLine{) ;

}
}
íSkổIí quả:
This ỉs a text; a - 123.456
789

M
Ket thuc.

Chú ý: Một cách khác để ghi dữ iiệu vào file. Tniớc hếỉ phải khai
báo biến file:
StreanMriter sw;

Tạo tìle text nhờ hàm CreateYextQ:
s t a t l c s t r in g f i l e l * " c : \ \ t e s t f i l e . t x t " ;
sw •= F i l e .C r e a t e T e x t ( f i l e l) ;
1 0 2


Ghi dữ liệu vào file:
sw .W riteLinerThis i s a t e x t ." ) ;

Sau khi ghi xong dữ liệu cần phải đóng file lại.
SM.Close 0 ;


Đọc dữliệu từíiie:
Khai báo đối tưỢng file:
StreanReader s r l;

Mở file:
s t r in g input;
s r l “ F ile .O p e n T e x t ( f ile l) ;

Đọc file:
input=srl.ReadToEnd();
Hiển ữiị dữ liệu sau khi đọc:
Console.W riteLíne(input);

I ? Ui dụ

8.2.
using System;
using System.10;
c la s s FileText

{
s t a t i c s tr in g f i i e l = "c : \ \ t e s t f i l e . t x t " ;
s t d t i c void Main(strlng[ 1 args)

i
StreamHritec sw; / / ghi du l i e u vao f í l e
sw = F ile .C r e a t e T e x t (f iie l) ;
sw.WriteLine("This i s a t e x t ." ) ;
sw.WriteLine{"Dai hoc Bach Khoa Ha Noi.");

sw.WriteLine("Trung tam Genetic Singapore.");
sw.WriteLine(123.456);
SM.Close();
StreamReader s r l ; / / doc du l i e u tu f i l e
/ / =* new StreamReader ( f i l e l ) ;

103


s t r in g input;
s r l * F ile .O p e n T e x t ( f ile l) ;
input « srl.ReadToEnđ0 ;
C onsole.W riteL ine(input);
Console .VíriteLine (**The end o f the stream!” );
s r l.C lo s e 0 ;
C onsole.ReadLine();

}
}
H k ể 'í quá:
Thìs is a text
Daí hoc Bach Khoa Ha Noi
Trung tam Genetic Singapore

123.456
Ta cũng có thể đọc file tíieo các dòng kế tiếp như đoạn mã dưới đây:
StreamReader sr;
s t r in g input;
s r “ F ile .O p e n T e x t ( f ile l) ;
while-(true)

if ( i n p u t »» n u lĩ) break;
C onsole.WriteLine(in p u t);

}
sr .C lo s e O ;

s

Ví dụ 8.3.
using System; .

using System. 10; •,
using System.Text;
c la s s FileText

{
s t a t í c s tr in g f i l e l = "c : \ \ t e s t f i i e . t x t " ;

104


s t a t i c doubie a * 123.456;
s t a t i c in t b

789;

s t â t i c char

* ’K';


s t a t i c void Main (stringỉ ) args)

{
using (5treamWriter sw « new StreamVíriter (f i l e l )

I
sw.Write ("This i s a te x t; a -

;

sw.WriteLine (a );
sw.VíriteLine (b);
5

W,W riteLine(kt);

sw.Clos€ ();

)
StreamReaàer sr;
s tr in g input;
sr « File.OpenText ( f i l e l );
w hile(true)

{
input * sr.ReadLine();
if ( in p u t “

null) break;


Console-W riteLine(input);
1

Console.WriteLíne (’*Ket thuc !'*);

sr.C lo se 0 ;
Consoie.ReadLine();

quá:

This is a text; a = 123,456
789
M
Ket Ihuc.
105


8. 2. G H I/Đ Ọ C FILE NHỊ PH Â N
Việc ghi/đọc dữ liệu của file nhị phân có nhiều ưu điểm hcAi ỉile text
vì bảo mật file cao hơn. ở đây sỗ trình bày cách ghi/đọc dữ liệu cho một
byte và cách ghi/đọc dữ liệu cho một đối tượng chúÈi nhiều trường dữ iiệu.
- Ghi dữ liệu vào file kiểu byte:
+ Giả sử ta khai báo một biến mảng kiểu
byte [ ] b l = { 1, 2, 3, 4, 255} ;

+ Khai báo đối tượng để ghì dữ liệu vào file "testbin.dat" ở ổ đĩa C;
F i l e S t r e a m ( " c : \ \ t e s t b i n . d a t ” , FileMode.OpenOrCreate,
P ile A c c e s s .W r ite , P iỉe S h a r e .N o n e );

+ Thựt hiện quá tìình ghi các phần tử của mảng số b l có kiểu byte:

foreach(byte bnext in bl)

{
sw.WríteByte(bnext);

}
Sau khi ghi xong, ta phải đóng fiie )ại.
sw .C lo se();

- E)ọc dữ liệu từ fi)e kiểu byte;
+ Mở file để đọc:
F ile I n fo fr » new F ile In fo r c : \ \ t e s t b i n .d a t ' ' );
stream strm ■ fr.OpenReađ<);

+ Sử dụng vòng lặp để đọc:
in t i ;
w hile(true)
i - strm.ReadBỵtỹO ;
if(i “

- 1 ) break/

C o n s o le .w r ite r { 0 ,4 )" , i ) ;
1

+ E>óng file sau khi đọc xong:
strm .C lose{)?
106

._



Ví dụ 8.4. Ví dụ này cho phép ta ghi và đọc các số có kiểu byte (giá

&

trị 0 ^ 255).
using System;
using Sỵsteni.IO;
c ỉ a s s P ileb in / / c a c so kieu bỵte

{
s t a t i c void Main (stringl ] args)

{
//G h i du l i e u tu f i i e vo i so kieu byte(0 4- 255) .
b yte [ ] b l ^ ị 255, 33, 44, 55, 6 6 } ;
P ileS trea m sw = new F ileStream (*'c : \ \ t e s t b i n . dat” ,'
rileMode.OpenOrCreate, F i l e A c c e s s , Writ 6 r F ile S h a r e .N o n e );
foreach(byte bnext in bl)
í

sw.W riteByte(bnext);
sw.Close (>;
/ / Doc đu ĩie u tu f i l e
F iie I n fo f * new F ile In fo (” c : \ \ t e s t b i n .dât” );
stream strm » f .OpenRead();
in t i/
w h ile(tru e)
.


{
i

=

s t r m .R e a d B y t e 0 /

i f ( i « - 1 ) breâk/
C onsole.W riter{ 0,4)

i);

)
stm ì-C lose {) /
Consoie. ReadLine()/

)
}
^ ^ K ể t quả:
255 33 44 55 66

107


Ta có thể thực hiện việc ghi/đọc dữ liệu của nhiều kiểu dữ liệu khác
nhau bằng file nhị phân.
- Ghi dữ liệu từ íile nhị phân;
s t r i n o f i l e l = " c :\\F ile B in l.d a t" ;
FileStreâfn f i l e l ;

s t r in g name; //d ữ l i ê u thành viên
double Sâlary; //d ừ l i ê u thành viên

/ / khai bảo đ 6i tượng wf cho v iê c ghi vào f i l e nhị phán
B inaryW riter wf * new B i n a r ỵ W r i t e r ;
/ / Các hàm Write {) để ghi từng thảnh vỉén
wf,Write(name);
w f.W rite(salary) /

“ Đọc dữ liệu từ íilc nhị phân:
Khai báo file cần đọc:
riieStream f i l e l ;
Khai báo đối tưỢng rf cho việc đọc:
BinarỵReađer r f « new B in a ry R ea d er(filô l);
Các hàm để đọc dữ liệu nhị phân:
name “ rf^R eadstring{);
s a la r y « r f . ReadDoiable ();

Phụ thuộc vào kiểu khai báo từng dữ liệu mà ta có các hàm đọc dữ
liệu khác nhâu.
b y te b l; b l * rfrP eâd B y te0 ;
char ch l; ch l « rf.ReadChar();
decimâl d l; d l * rf.ReađDecimal();
double d2; d2 « r f . ReadDoưble();
f l o a t f l ; f l » r f.R e a d s in g le 0 ;

i n t a; a * rf,R e a d In t3 2 ();
long b; b * rf• R e a d ln t6 4 í);
sb y te s b l / sb l * r f •ReađSByteO;
u in t u i l ; u i l “ rf-R eadưlnt32{);

ulong u l l ; u l l = rf.ReadUInt640 ;
108


Vi dụ 8.5.
using System;
using System.10;
c la s s FiieBin2

(
p riv a te s tr in g name;
p riv a te in t age;
p riv a te double salary;
public FileBin2()

I
name “
agè =

0

;

salary = ũ;

}
public F iÌ€ B ir2 (strin g name, int âge, đouble Sâlary)

{
this.name = name;

t h is .a g e * age/
t h i s . s â l a r y » Sâlary;

)
public void Inputo

(
Console.Vírite ("\ nNhap ten: **);
name * Console.ReadLine0 ;
Consoỉe. W rite("Nhap t u o i : " );
age = Int32»Parse(Console.ReadLine ( ) ) ;
C onsole,W rite("Nhap ĩuong: ” );
sa la ry = Double. Parse(ConsoÌe.ReadLine());

)
public void Show()
Console.WriteLine(’'Ten: *'+name+''; Tuoi: ’.'+age);

109


C onsole.W riteL ineL uong: **+saLary);

)
public void SaveData(FileStream f i l e l )
BinaryWriter wf * new BinarỵVỉriter

;

wf.Write (name);

wf .Vírite (age);
wf .W rite(sa la ry );

}
public void ReađData(FileStream f i l e l )

{
BinaryReader r f * new B i n a r ỵ R e a đ e r /
name « r f .ReadStringO
age * rf.R ea đ ln t3 2 0 ;
salarỵ * r í . ReadDouble();

}
public void MenuO

{
Console.WriteLine (”

MENƯ

Console.VíriteLine (” ■«■......

' ^

");
);

Console • VíriteLine (" 1, Nhap du lie u ” );
Console.WriteLine <"2• Doc va xem ");
Console. WriteLine (” 3 • Thoat” );

Console,WriteLine (" ■■iLUi—

)•

Console• WriterNhap so 1 - 3 de lua chon: ");

}
)
c la s s T estP ile

{
s t a t i c voíd Main (string[ ] args)

{
FileBin2 p » new F ileB in 2();

1 1 0


s t r in g filenam e = ” c :\\D a tâ .d a t’*;
s t r in g choice = ”

;

w h ile (c h o ic e !» ” 3")

{
p.Menu 0 ;
ch o ice * Console.ReadLine0 ;
sw itch (ch oice)


{
Câse ” 1*’ : Console.WriteLine

Save data to

EileStream fwr * new r ile S tr e a m (fiien a m e,
EileM ođe. C reate, r i l e A c c e s s . Write^ r i l e S h a r e . W r ite );
p » new F ileB in 2();
p.Input

0

/

p . SaveData(fwr);
fw r.C lose 0 ;
break;
ca se ” 2": Consoie.WriteLine ("Read dâtâ from f i l e ” );
F ilestream fr
new F ile S tr e a m (fiie n a m e , PileMode.Open,
F ile A c c e s s .R e a d , r ile S h a r e .R e a đ ) /
p »,new F ileB in2();
p,R eađD ata(fr)r
p. Show(>;
break;
ca se ” 3" : continue;

}


H K ề t quầ:
MENU
1. Nhap du lleu

2. Doc va xem
1 1 1


3. Thoat

Nhap so 1 - 3 de lua chon: 1
Save daĩa to file
Nhap ten: Hoa
Nhap tuoi; 22
Nhap luong: 1000

MENU
1. Nhap du líeu
2. Doc va xem
3. Thoat
Nhap so 1 - 3 de lua chon: 2
Read data from file
Ten: Hoa; Tuoi; 22
Luong: 1000

Việc ghi/đọc bằng file nhị phân có thể ử>ụt hiện cho một mảng đối
íuọng. Mỗi đối tuỵng lại bao gồm nhiểu kiểu dữ liệu thành phần khác nhau.
Ví dụ 8.6. Viết chutữìg trinh để lưu dử iiệu vào file.

using System;

u sing System. 10;
c l a s s FileBin3


p r iv â te s tr in g nâine;
p r iv a te i n t age;
p r iv a te double salary;
p u b lic FileBin3()

age «
1 1 2

0

;


sa la ry *

0

;

t

public voíd Inputo

I
C o n s o le . W r ite c*\ nH hap te n :


'*);

name = Console.ReadLine 0 ;
Cofisole,Write (”Tuoi: '*);
age = Int32.Parse(Consoie.ReâdLine());
Console,Write

Luong: *');

Sâlary = Double.Pârse(Conscle.ReadLine0 ) ;

}
p u b lic

v o id

S h o w ()

(
C on sole.M riteL in eD oc du iie u tu
Console.MriteLine ("Ten ” -*-najne+” ; Tuoi:"

;

Console. WriteLine("Luong: "+ sa lâ r y );

)
p u b lic

v o id


S a v e D â ta (rỉie S tre a m

BinaryVĩriter wf = new BinarỵWriter ( f i l e l ) ;
w f . W r i t e < nam e);

wf .Vírite <âge);
w f.W rite(sa la ry );

í
p u b lic

\
v o id

R e a đ D a ta (F ile S tre a m

file l)

{
BinaryReader r f * new BinarỵReader ( f i l e l ) ;
name = rf.R eadString 0 ;
age = rf.R ea d ln t3 2 ();
S â la r ỵ

«

r f• R e a d D o u b le {> ;

113



c lâ s s T e s t r ile
s t a t i c void Main (stringC ] args)
in t n;
Ccnsole.VíriteTNhap n *
n » Iĩìt32.Parse(Console^ReadLine( ));
FileBiiì3 [] p = new FileBin3[ n) ;
str in g filename » ” c:\\Data.đat**;
Con$ole.WriteLineCGhi du lie u vao f i i e ” );
FileStream fwr * new FileStream(filename, FileMode.Create,
FileA ccess,W rite/ F ileShare.w rit e ) ;
f o r ( in t i *

0

; i < n; i++)

{
i] * new FileBin3 ();
Ịi i) ,Input 0 ;
f( i] .SaveData (fwr);
1

fwr.Close () /
/ / --------------------------------------------------------------------

Console,WriteLine{’*Doc du líe u tu f i l e ” );
FileBin3 [ ] p i “ new FileBini^ n] ;
rileStream f r = new FileStream(filenam e, rileMode.Open,

PileAccess.Read, r ile S h â r e . Read);
f o r ( in t i *

0

; i < n; i++)

{
pK i) “ new F ileB ín 3();
pl[ i} .ReadĐata(fr);
pl[ i] .Show() ;

}
Console. ReadLine ();

}
)
114
1 L l Ậ P 'n ề ề i . . H O M


^ ^ K ể t quả:

Nhap n = 2
Ghi du lieu vao fìle
Nhap ten: Mai
Tuoi: 22
Luong: 1000
Nhap ten: Ha
Tuoi: 35

Luong: 2000
Doc du lieu tu fìle
Ten: Mai: Tuoi: 22
Luong: 1000
Doc du lieu tu file
Ten; Ha; Tuoi; 32
Luong; 2000
G v i dụ 8.7. Xây dựng m ột menu để thụt hiện các thao tác: Nhập, liệt

kê, xoá, sửa. tim kiêm, bổ sung.
using System; //C on soie.A pp lication
c la s s person

i
p riv a te s t r in g narne;
p riv a te long ID;
p riv a te in t age;
/ / --------------------------------------------------------------------

personO

Public

name =

;

ĨD = 0;
age =


0

;

/ / ......... ...... ............................................... .............. ......
115


public s t a t i c in t n;
public person (] p = new person'

100

];

/ / ------ ------------------------------ -------------------------pubĩic void InputO
I

f o r ( in t i =

0

; i < n; Ì++)

(
p( i] = new p erso n O ;
Console .WriteLine ("person { 0) " , i ) ;
Console.VỉriteLine ("Enter name: ");
p( i] .name = Console.ReadLine 0 ;
Console.WriteLine("Enter ID: ");

p( iỊ .ID = Int64 .Parse (Console.ReadLíne 0 ) ;
Console.KriteLine("Enter age: ");
p; i] .age = Int32. Parse (Console.ReađLine {)) ;
ì

}
/ / ------------------------------------- -------------------------pidDlic void Show()

t
f o r ( in t i * 0 ; i < n;
CcnsOÌe.WEiteLine("Name:{ 0) ; ID:{ 1} ; age: {2}" , Fp{ i] .ID, ri i] .age) ;
1

-----------------------------------------------------------------public void SearchNameO

(
str in g namel;
Consoie.VIrite ("Enter nante t o search: ” );
namel “ Console.ReadLine();
f o r ( in t i *

0

; i < n; i++)

{
i f (String.Ccsnpare (namel, F( i] .name) ** 0)
116



C onsole.V ỉriteL ine ("Name; f CỊ ; ID: ( l } ; a g e : 12}",
p[ i] .naine, p{ ij .ID, p[ i] .a g e);

}
)
/ / ------------------------------------ --------- -------------------

public void SearchlDO

i
long id l;
C onsole.W rite("Enter ID to search: ” );
i d l = In t6 4 . Parse{Consoie.ReadLine());
f o r ( i r t i = Ũ; i < n; i++)

{
i f (ídl “= p( i] . ID)
Consoie .VỈriteLine (" Narre: { 0 } ; ID: I 1} ; age : { 2} ",
pliỉ.naĩre, p[ i ] , I D, p( i ] . a g e ) ;

)
}
/ / --------------------------------------- ------------ ............ public void DeleteO

{
long id l;
C onsole.W rite("Enter ID to search: ");
i d l = Int64. Parse(Console.ReadLine());
f o r ( in t i = 0; i < n; Ì++I


{
i f (id l == FÍ il -ID)

{
Console.VỉriteLine (" Name:i 0} ; ID:{ 1) ; age: {2}", p( i] .name,
p. i] .ID, p( i) .age) ;
w h ile (i < n)

{
i) = p( i+ i] ;
i++;

1 1 7


n = n - i;

/ / ------------------------------------- ------------------- --public void E d it o

{
s tr in g namel;

C onsole.W rite("E nter name to search: ” );
namel * Console.ReadLine();
f o r ( in t i = 0 ; i < n; i++)

{
i f (String.Ccxnpare (namel,p( ij .name) == 0)


í
C onsole.V íriteLine {" Narae: ( 0 ) ;
Pí i] .name, p [ i ] . I D , p [ i ] . a g e ) ;

ID: { 1 } ; age: { 2 ) " ,

Console.KriteLine {" person { 0) ” , i) ;
Console.WriteLine("Enter name: ” );
p{ i] . name “ Console. ReaoLine () ;
C onsole.K riteL inerEnter ID: '•);
p( i]

.1 0

* Int64 .ParseíConsole.ReadLine {)) ;

Console.WriteLine(” Enter age: ");
p( i) .age - Int32.Parse(Console.ReadLine {)) ;

}
/ / -------------------------------------public void AppenđO

I
p( nl “ new personO ;
Console.WriteLine C’Enter name: ” );
fị n] .name * Console.ReadLine
118

0


;


Console.VíriteLine(” Bnter ID: ” );
fị nì .ID » Int64,Pârse{Console.R6ddLine{));
Console.WriteLineTEnter age: ");
p( n] ,age ® Int32.Parse (Console.ReađLineO );
n * n 4* 1 ;

)
/ / - ....... ............................................. ........................
p ublic s t a t i c void MainO

(
person per * new personO;
int choice = 0 ;

do

(
Console. WriteLine r* MENU ” );
Console.W riteLine(" 1. Input D a ta ’M;
Console-VíriteLiner 2. L ist A ll **);
Console. WriteLine r

3• Edit (Name) ");

Console.writ e L in e r 4. Search Name ");
Console.WriteLine(" 5, Search ID " )/
Console.W riteLine("


6

, Delete

Console.W riteLine(** 7, Append");
C o n s o l e . W r i t e L i n e 8 . Exit **);
C o n so le.H riter Bnter Choice:")/
chcice ■ Int32.Parse(Console.R€âdLỉnê());

sw itch(choice)

{
case 1: Console.Write("Enter niiinber o f persons: '*);
n » Int32.Parse(Console.ReadLine( ));
per.Input 0 ;break;
case 2: per.Show();break;
case 3: p e r .E d it 0 ;bredk;
case 4: per .SearchKaine 0 ;break;

119


case 5: p er.S earch lù d ;break;
case

6

: p e r .D e le t e ( ) /break;
t


case 7: ger.Append0 ;break;
Câse 8: continue;

}
}
w h ile(ch o íce !=

8

);

//
^ ^ K ế t quá sau khi chạy chương trình được biểu diễn trên hình 8.3.

« C :\C o lle c C # 0 6 \C S h a r p 0 4 \
Ent^r Age :
HENU
t . ỉnput Oata
2. Lict All
3. £cỉit (Nam«)
^ . S^arch Nône
5 s^arch ID
ĩ. Append
Exit
Ent^r Choice : 2
Ndmp :Nga ; 1 0 . 11 1
I^9 e : 26
Mai
10

222
: 25
tình ; 10
333 r ^99 : 28
MENU
1
Input Data
2 Li st Pi l
J tdLt (Nâm«)
^ S^drch
5. s«?arch 10
8

.

7 í^pp^nd
ô ExW
Ent«r Choic« •
Hình 8.3

Vi dụ 8 .8. Ví dụ này đuục coi là một bài tập dài trong cuốn Lập trình

c # từ cơ bản đến nâng cao. Yẻu cầu của bài tập này như sau;
Công ty tmyền thông ABC giữ vai trò quan trọng trong sự phát triển

1 2 0


vé công nghiệp điện thoại cùa khu vụt. Yêu cầu bạn phải phát triển một
hệ thống thông tin để quản lý bằng máy tính vể điện thoại nhằm cung

cấp cho khách hàng sự hỗ trỢ những thông tin cần thiếtCác yêu cầu đặt ra như sau:
1. Tạo một lcfp phone để lưu các

dữ tiệu sau:

Phone number
Pullname
Address
No Of Line
Type
Orgdnizaíion
2. Dử liệu này cần phải được:
a) Khcfi tạo nhờ hàm tạo (constructor)
b} Truy cập dữ liệu nhờ sử dụng thuộc tính (properties)
3. Lớp phone phải có phương thức để lưu đối tượng nhờ iớp
PiieStream.
4. Tạo một lcfp phone book để lưu toàn bộ lớp phone vào trong một
mảng.
5. Trong lớp phone book phải sửdụng Indexer để sao cho ta có thể
truy cập vào tCíng phần tử của mảng phone.
6. Ngưcí sử dụng phải thựt hiện đưỢc các chủt năng sau:

a) Add New (thêm bản ghi mới)
b) Edií (sửa đổi một bản ghi)
c) Delete {xoá một bản ghi)
d) Tim một bằn ghi trong mảng phone {tìm theo tên và tìm theo số

điện thoại)
e) Hiển thị các số đ ệ n thoại khẩn cấp
Duứi đây liệt kê toàn bộ chương trình của bài tập dài nêu trên.

/* ProgrartBning using c# - Examples
' Project 1: Telephone inquirỵ system
121


• In c ld s s PhoneBook: an array c f phcnes i s implemented
by an ArrayList in sta n c e
* F i l e I/O: binarỵ f i l e , FileStrea-Tj i s processed with
BinaryWriter/BinaryReader

*/
ưsing Systein;
using System. 10;
using S ystem -C cllection s;
c l a s s Phone
p r iv a te ulcng phoneNumber;
p r iv â te s t r in g fullName;
p r iv a te s t r in g adđress;
p r iv a te i n t noOfLíne/
p r iv â te s t r in g type;;
p r iv a te s t r in g organization;
p u b lic Phonelụiong phoneNumber, s t r i n g fuilNâme, s t r in g
adđress, in t noOíLine, s t r ỉn g type, strir.g organizâtion)

{
this.phoneNunổDer » phcneN^imber;
th is,fu llN a m e = fullName;
this^address

* ađdress/


t h i 3 .no 0 fLine “ noOfLine;
th is^ ty p e =*■ type;
t h is .o r g a n ie a tio n « organi 2 â ‘.ion;
1

p u b lic PhoneO: t h i s (0/

0,

{}

p u b lic ulong ĩ^oneNumber

{
get{ return phoneNun*iber;)
setí phoneNumber » valu e;l

}
p u b ỉic s t r in g FuliName

122

n.dị^wỀmi.JtíM


uet{ r e t u r n íullKame;}

seti fullKame « value;)


}
p u b lic

>
S ũ rin g

A tíd re i^ s

get{ return th is.â d đ r e ss;}
set{ address = value;)

)
p u b lic in t noOíLine
í
getỉ return noOfLine;)
se tí noOfLine = value;)

}
p u b lic

s tr in g

T ype

{
oetị return type;}
set{ type = value;i

)
p u b iic s tr in g Organization


{
get( return orgânization;)
s e ti cr^aní 2 a tio n = value;}

}
publÌc void Inputíỉ

{
Console.Write r Phone nisTử>er:
phoneNumber * ƯInt64.ParseConsole,Write r F u ll name: '•) ;
fullName « Consolế.ReadLineO;
C onsole. Write í” Address: ” ) /
address * C onsole. ReadLine();
Console.W rite(”No o f i i n e :

,

noOfLine « In r32.P arsetC onsole.R eadL ine());
Console.Vírite("Tỵpe: ");
1 2 3


type * Console.ReadLine();
Console.Write (”Orgânization:

);

organizâtion « Console.ReadLine ();


)
p u b lic void DisplayO

{
//Console.W riteLíne(ToString {)) /
Console,WriteLine rTelephone Nurrber:\t{ 0, ••40} Lines:
ị 1, 5]**, phoneNuiTìber, noOfLine) ;
Console-WriteLine {" Name/0 rgani 2 a tic n : \t " +fullName+ " / "
+ o r g a n iz a tio n );
Console .VíriteLine (*'Address:\ t \ t” + address};
Console.VỉriteLine ( * ' T y p e : \ t \ t \ + type) ;

)
p u b lic override s tr in g ToStringO

{
Return (String.Format (’*Phone: { 0) \nName: { ỉ}\nAddress:
{ 2) \nL ine: { 3} \n T ^ e : { 4} \nOrg: ( 5}
phoneNumber, fullName,
addresố, noOíLine, type, o r g a n iz a tio n ));

)
/ / p u b l i c voíd Save(FileStream fs)
p u b lic void Sdve{BinaryWriter bw)

l
//Bm«^ryWriter bw * new fìinaryWriter ( f s ) ;
bw.Write (phoneNumber) /
bw.Write (fullName) ;

bw.Write (address);
bw. Vlrite (noOfLineị;
bw.Write (ty p e);
bw.Write (organiĩation) /
//b w .C lo s e 0 ;

p u b lic void Load(Bi^arỵReader br)

{
124


phoneNumber s? b r. ReadUInt64 ();
fullName = b r . ReadString ();
address * b r.R ead strin g0 ;
noOíLine = br.R eadlnt320 ;
type * br.ReadString0 ;
organixation » br .ReadStringO ;

c la s s PhoneBook
ArrayList data * new ArraỵListO ;
//dynamic array o f o b ie c ts
public Phone thist in t i] / / indexer

{
get

(
if


((-1

< i) && (i < data.Count))

return (Phone)data[ i] ;
e lse
throw new InđexOutOíRangeException (" Index out of range**)#

}
set

(
if

((-1 < i) &ỉt (i < data.Count))

/ / changé a phone
data( i] « Vâlue;
e l s e i f (i “ dâta.Count)
/ / adđ new phone
d a ta .Add(value);
e lse
throw new IndexOutOíRangeException("Index out of range” );

\
1

p u b lic void ClearO
1 2 5



×