Dia Mejor

Proyecto

Author: Moises
 
 

Practica 9.4

Author: Moises

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Problema4
{
class Program
{
static void Main(string[] args)
{
ArregloBidimensional Reticula = new ArregloBidimensional(10, 29);
int ave, calle, noac, cont;

do
{
Console.Clear();
Console.WriteLine("Registro de accidentes\n");
Console.Write("Avenida: ");
ave = int.Parse(Console.ReadLine());
Console.Write("Calle: ");
calle = int.Parse(Console.ReadLine());
Console.Write("# accidentes: ");
noac = int.Parse(Console.ReadLine());

Reticula.AsignarDato(ave - 1, calle - 30, noac);
Console.Write("Presione 1 para continuar");
cont = int.Parse(Console.ReadLine());
}
while (cont == 1);
Console.Clear();
double PrimerMayor = Reticula.DatoMayor(10, 29);
int PrimerIndiceR = Reticula.indRenglon;
int PrimerIndiceC = Reticula.indColumna;
Reticula.T1[PrimerIndiceR, PrimerIndiceC] = 0;
double SegundoMayor = Reticula.DatoMayor(10, 29);
int SegundoIndiceR = Reticula.indRenglon;
int SegundoIndiceC = Reticula.indColumna;
Reticula.T1[SegundoIndiceR, SegundoIndiceC] = 0;
double TercerMayor = Reticula.DatoMayor(10, 29);
int TercerIndiceR = Reticula.indRenglon;
int TercerIndiceC = Reticula.indColumna;


Console.WriteLine("No. Accidentes \tAvenida \tCalle");
Console.WriteLine("1. "+PrimerMayor + "\t\t" + PrimerIndiceR + "\t\t" + PrimerIndiceC);
Console.WriteLine("2. "+SegundoMayor + "\t\t" + SegundoIndiceR + "\t\t" + SegundoIndiceC);
Console.WriteLine("3. "+TercerMayor + "\t\t" + TercerIndiceR + "\t\t" + TercerIndiceC);

Console.ReadKey();
}
}
}

 

Practica 9.3

Author: Moises

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Problema3
{
class Program
{
static void Main(string[] args)
{
int M, N, R, C, Valor=0;
double suma;

Console.Write("Escribe el numero de renglones");
M = int.Parse(Console.ReadLine());
Console.Write("Escribe el numero de columnas");
N = int.Parse(Console.ReadLine());

ArBidim A = new ArBidim(M,N);

//faltan datos (falta arreglo?)
Arreglo X = new Arreglo(N);
Arreglo Y = new Arreglo(M);

for (R = 0; R < M; R++)
{
for (C = 0; C < N; C++)
{
Console.Write("Introduce Valor A[" + (R + 1) + "," + (C + 1)+"]: ");
Valor = int.Parse(Console.ReadLine());
A.T1[R, C] = Valor;

}
}

Console.WriteLine("Introduce los siguientes valores: ");

for (C = 0; C < N; C++)
{
Console.Write("X[" + (C + 1) + "]: ");
Valor = int.Parse(Console.ReadLine());
X.AsignarDato(C, Valor);
}


for (R = 0; R < M; R++)
{
suma = 0;

for (C = 0; C < N; C++)
{
suma = suma + A.T1[R, C] * X.ObtenerDato(C);
}

Y.elementos[R] = suma;
}
Console.WriteLine("Matriz");
for (R = 0; R < M; R++)
{
for (C = 0; C < N; C++)
{

Console.Write("\t{0}",A.ObtenerDato(R, C));
}
Console.WriteLine();

}
Console.WriteLine("\n\n");

for (C = 0; C < N; C++)
{
Console.Write("X[" + (C + 1) + "] = ");
Console.WriteLine("\t{0}",X.ObtenerDato(C));
}
Console.WriteLine();
for (R = 0; R < M; R++)
{
Console.Write("Y[" + (R + 1) + "] = ");
Console.WriteLine("\t{0}",Y.ObtenerDato(R));
}
Console.ReadKey();


}
}
}

 

Practica 9.2

Author: Moises

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace A_Bid_2_Visual
{
public partial class Form1 : Form
{
Arreglo Articulos = new Arreglo();
ArregloBidimensional ventas = new ArregloBidimensional(20, 50);
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
listBox1.Visible = false;
RbSi.Checked = true;
}

private void BtAceptar_Click(object sender, EventArgs e)
{


int Num, NoArt, Ven;

Num = int.Parse(textBox1.Text);
NoArt = int.Parse(textBox2.Text);
Ven = int.Parse(textBox3.Text);
ventas.T1[Num - 1, NoArt - 1] = Ven;


listBox1.Items.Clear();
listBox1.Items.Add("Calculo de sueldos");
listBox1.Items.Add("No Vendedor \tTotal Venta \tSueldo");

int R, C;
double suma, sueldo;
for (R = 0; R < 20; R++)
{
suma = 0.0;
for (C = 0; C < 50; C++)
{
suma = suma + ventas.ObtenerDato(R, C) * Articulos.ObtenerDato(C);
}
sueldo = suma * 0.05;

listBox1.Items.Add((R + 1) + "\t\t" + suma + "\t\t" + sueldo);

}


if (RbNo.Checked == true)
{
listBox1.Visible = true;
BtAceptar.Visible = false;
button1.Visible = false;
groupBox1.Visible = false;
groupBox2.Visible = false;
}
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}

private void BtSalir_Click(object sender, EventArgs e)
{
Close();
}

private void button1_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}
}
}

 

Practica 9.1

Author: Moises

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Practica8_Vendedor_Visual
{
public partial class Form1 : Form
{
Vendedor [] compa = new Vendedor[25];
Arreglo A1 = new Arreglo(25);
int posmay, posmayor;

public Form1()
{
InitializeComponent();

groupBox1.Visible = true;
BtContinuar.Visible = false;
BtTerminar.Visible = false;
BtAceptar.Visible = true;
BtCancelar.Visible = true;
label4.Text = "";
label5.Text = "";

}

private void BtAceptar_Click(object sender, EventArgs e)
{
int no;
string nom;
double monto;

no = int.Parse(textBox1.Text);
nom = textBox2.Text;
monto = double.Parse(textBox3.Text);


Vendedor Vx = new Vendedor(no, nom, monto);
compa[no - 1] = Vx;

A1.AsignarDato(no, monto);
posmay = A1.Mayor(25);
posmayor = posmay;

BtContinuar.Visible = true;
BtTerminar.Visible = true;
BtAceptar.Visible = false;
BtCancelar.Visible = false;

}

private void BtTerminar_Click(object sender, EventArgs e)
{
int I;
listBox1.Visible = true;
groupBox1.Visible = false;
BtContinuar.Visible = false;
BtTerminar.Visible = false;
BtAceptar.Visible = false;
BtCancelar.Visible = false;
listBox1.Items.Add("No. Vendedor \tNombre Vendedor \tMonto Venta");
for (I = 0; I < 25; I++)
{
if (compa[I] != null)
{
listBox1.Items.Add("" + compa[I].ObtenerNo_Vend() + "\t\t" + compa[I].ObtenerNombre() + "\t\t" + compa[I].ObtenerVentaTotal());
}
}



label4.Text = "Primer mayor: "+posmayor.ToString() + " " + A1.ObtenerDato(posmayor).ToString();



A1.AsignarDato(posmayor, 0);

posmay = A1.Mayor(25);
posmayor = posmay;



label5.Text = "Segundo mayor: " + posmayor.ToString() + " " + A1.ObtenerDato(posmayor).ToString();



}
private void BtContinuar_Click(object sender, EventArgs e)
{
groupBox1.Visible = true;
BtContinuar.Visible = false;
BtTerminar.Visible = false;
BtAceptar.Visible = true;
BtCancelar.Visible = true;
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}

private void BtSalir_Click(object sender, EventArgs e)
{
Close();
}

private void BtCancelar_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}
}
}

 

Practica 8.3

Author: Moises

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Practica8_Vendedor_Visual
{
public partial class Form1 : Form
{
Vendedor [] compa = new Vendedor[25];
Arreglo A1 = new Arreglo(25);
int posmay, posmayor;

public Form1()
{
InitializeComponent();

groupBox1.Visible = true;
BtContinuar.Visible = false;
BtTerminar.Visible = false;
BtAceptar.Visible = true;
BtCancelar.Visible = true;
label4.Text = "";
label5.Text = "";

}

private void BtAceptar_Click(object sender, EventArgs e)
{
int no;
string nom;
double monto;

no = int.Parse(textBox1.Text);
nom = textBox2.Text;
monto = double.Parse(textBox3.Text);


Vendedor Vx = new Vendedor(no, nom, monto);
compa[no - 1] = Vx;

A1.AsignarDato(no, monto);
posmay = A1.Mayor(25);
posmayor = posmay;

BtContinuar.Visible = true;
BtTerminar.Visible = true;
BtAceptar.Visible = false;
BtCancelar.Visible = false;

}

private void BtTerminar_Click(object sender, EventArgs e)
{
int I;
listBox1.Visible = true;
groupBox1.Visible = false;
BtContinuar.Visible = false;
BtTerminar.Visible = false;
BtAceptar.Visible = false;
BtCancelar.Visible = false;
listBox1.Items.Add("No. Vendedor \tNombre Vendedor \tMonto Venta");
for (I = 0; I < 25; I++)
{
if (compa[I] != null)
{
listBox1.Items.Add("" + compa[I].ObtenerNo_Vend() + "\t\t" + compa[I].ObtenerNombre() + "\t\t" + compa[I].ObtenerVentaTotal());
}
}



label4.Text = "Primer mayor: "+posmayor.ToString() + " " + A1.ObtenerDato(posmayor).ToString();



A1.AsignarDato(posmayor, 0);

posmay = A1.Mayor(25);
posmayor = posmay;



label5.Text = "Segundo mayor: " + posmayor.ToString() + " " + A1.ObtenerDato(posmayor).ToString();



}
private void BtContinuar_Click(object sender, EventArgs e)
{
groupBox1.Visible = true;
BtContinuar.Visible = false;
BtTerminar.Visible = false;
BtAceptar.Visible = true;
BtCancelar.Visible = true;
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}

private void BtSalir_Click(object sender, EventArgs e)
{
Close();
}

private void BtCancelar_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}
}
}

 

Practica 8.2

Author: Moises

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Formula_visual
{
public partial class Form1 : Form
{

Arreglo H = new Arreglo();
Arreglo F = new Arreglo();
int I=0;
int Num;

public Form1()
{
InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)
{
textBox3.Enabled = false;
label1.Text = "H[" + (I + 1) + "]:";
label2.Text = "F[" + (I + 1) + "]:";
}

private void button2_Click(object sender, EventArgs e)
{

double dat1, dat2;
Num = int.Parse(textBox3.Text);
if (I < Num)
{
label1.Text = "H[" + (I + 2) + "]:";
dat1 = double.Parse(textBox1.Text);
H.AsignarDato(I, dat1);
label2.Text = "F[" + (I + 2) + "]:";
dat2 = double.Parse(textBox2.Text);
F.AsignarDato(I, dat2);
I++;
textBox2.Clear();
textBox1.Clear();

}
if (I == Num)
{
double s = 0.0;
for (I = 0; I < Num; I++)
{
s = s + H.ObtenerDato(I) * F.ObtenerDato(I);
}
double Numerador = Num * s - H.SumaDatos(Num) * F.SumaDatos(Num);
double D = (Num * H.SumaCuadrada(Num) - H.SumaCuadrada(Num)) * (Num * F.SumaCuadrada(Num) - F.SumaCuadrada(Num));
double Denominador = Math.Sqrt(D);
double r = Numerador / Denominador;
label3.Visible = true;
label3.Text = ("El Valor de R es: " + r);
}
}
}
}

 

Practica 8.1

Author: Moises

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Ejercicio_Arreglos_Visual
{
public partial class Form1 : Form
{
int j;
int venta;
Arreglo VentaAnual = new Arreglo(12);

public Form1()
{
InitializeComponent();
}

private void BtSalir_Click(object sender, EventArgs e)
{
Close();
}

private void Form1_Load(object sender, EventArgs e)
{
groupBox1.Visible = true;
groupBox2.Visible = true;
listBox1.Visible = false;
textBox1.Enabled = true;
listBox1.Enabled = false;
radioButton1.Checked = true;
RbEnero.Checked = true;
textBox3.Visible = false;
}


private void BtOK_Click(object sender, EventArgs e)
{

groupBox1.Visible = true;
groupBox2.Visible = true;
if(RbEnero.Checked==true)
{
j = 1;
}
else
if (RbFebrero.Checked == true)
{
j = 2;
}
else
if (RbMarzo.Checked == true)
{
j = 3;
}
else
if (RbAbril.Checked== true)
{
j = 4;
}
else
if (RbMayo.Checked == true)
{
j = 5;
}
else
if (RbJunio.Checked == true)
{
j = 6;
}
else
if (RbJulio.Checked == true)
{
j = 7;
}
else
if (RbAgosto.Checked == true)
{
j = 8;
}
else
if (RbSeptiembre.Checked == true)
{
j = 9;
}
else
if (RbOctubre.Checked == true)
{
j = 10;
}
else
if (RbNoviembre.Checked == true)
{
j = 11;
}
else
if (RbDiciembre.Checked == true)
{
j = 12;
}

venta = int.Parse(textBox1.Text);
VentaAnual.AcumularDato(j - 1, venta);
textBox1.Clear();


if (radioButton2.Checked == true)
{
groupBox1.Visible = false;
groupBox2.Visible = false;
groupBox3.Visible = false;
listBox1.Visible = true;


for (j = 0; j < 12; j++)
{

switch (j)
{
case 0: listBox1.Items.Add("Enero=" + VentaAnual.ObtenerDato(j));
break;
case 1: listBox1.Items.Add("Febrero=" + VentaAnual.ObtenerDato(j));
break;
case 2: listBox1.Items.Add("Marzo=" + VentaAnual.ObtenerDato(j));
break;
case 3: listBox1.Items.Add("Abril=" + VentaAnual.ObtenerDato(j));
break;
case 4: listBox1.Items.Add("Mayo=" + VentaAnual.ObtenerDato(j));
break;
case 5: listBox1.Items.Add("Junio=" + VentaAnual.ObtenerDato(j));
break;
case 6: listBox1.Items.Add("Julio=" + VentaAnual.ObtenerDato(j));
break;
case 7: listBox1.Items.Add("Agosto=" + VentaAnual.ObtenerDato(j));
break;
case 8: listBox1.Items.Add("Septiembre=" + VentaAnual.ObtenerDato(j));
break;
case 9: listBox1.Items.Add("Octubre=" + VentaAnual.ObtenerDato(j));
break;
case 10: listBox1.Items.Add("Noviembre=" + VentaAnual.ObtenerDato(j));
break;
case 11: listBox1.Items.Add("Diciembre=" + VentaAnual.ObtenerDato(j));
break;
}
}
textBox3.Visible = true;
textBox3.Text = "La venta anual es " + VentaAnual.suma(12);
}
else
{
groupBox1.Visible = true;
listBox1.Visible = false;

}

}
}
}

 

Resumen Archivos y flujos

Author: Moises

1. Introducción

Las variables y los arreglos ofrecen sólo un almacenamiento temporal de los datos; los datos se pierden cuando una variable local "queda fuera de alcance" o cuando el programa termina. En cambio los archivos pueden retener información incluso después de cerrar la aplicación.

2. Jerarquia de datos

Los datos básicos que maneja una computadora son ceros y unos, en otras palabras código binario. El elemento mas pequeño en el manejo de datos es el bit o digito binario al cual se le asigna el valor de cero o uno.

Aunque tienen mucha utilidad, es mas fácil para los programadores utilizar digitos decimales, caracteres y simbolos especiales. Un campo es un grupo de caracteres que transmiten cierto significado.

Los elementos de datos procesados por las computadoras forman una jerarquía de datos en la cual los datos de los elementos se hacen mas grandes y mas complejos en estructura, a medida que progresamos de bits a caracteres, de caracteres a campos y de campos a conjuntos de datos mas grandes.

Un registro esta compuesto de varios campos relacionados. Un conjunto de registros conforman a un archivo.

3. Archivos y flujos

Cuando se abre un archivo, se crea un objeto que se asocia con un flujo. Cuando se ejecuta un programa, el entorno en tiempo de ejecución crea tres objetos flujo, a los cuales se puede acceder con las propiedades Console.Out, Console.In y Console.Error. El primero es sobre lectura de información, el segundo de ingresar información y el tercero permite desplegar mensajes de error. El espacio de nombres System.IO cuenta con clases de flujos como StreamReader, StreamWriter y FileStream.

4. Las clases File y Directory

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.IO;

// displays contents of files and directories

public class FileTestForm : System.Windows.Forms.Form

{

private System.Windows.Forms.Label directionsLabel;

private System.Windows.Forms.TextBox outputTextBox;

private System.Windows.Forms.TextBox inputTextBox;

private System.ComponentModel.Container components = null;

[STAThread]

static void Main()

{

Application.Run( new FileTestForm() );

}

// Visual Studio .NET generated code

// invoked when user presses key

private void inputTextBox_KeyDown(

object sender, System.Windows.Forms.KeyEventArgs e )

{

// determine whether user pressed Enter key

if ( e.KeyCode == Keys.Enter )

{

string fileName; // name of file or directory

// get user-specified file or directory

fileName = inputTextBox.Text;

// determine whether fileName is a file

if ( File.Exists( fileName ) )

{

// get file's creation date,

// modification date, etc.

outputTextBox.Text = GetInformation( fileName );

// display file contents through StreamReader

try

{

// obtain reader and file contents

StreamReader stream = new StreamReader( fileName );

outputTextBox.Text += stream.ReadToEnd();

}

// handle exception if StreamReader is unavailable

catch( IOException )

{

MessageBox.Show( "File Error", "File Error",

MessageBoxButtons.OK, MessageBoxIcon.Error );

}

}

// determine whether fileName is a directory

else if ( Directory.Exists( fileName ) )

{

// array for directories

string[] directoryList;

// get directory's creation date,

// modification date, etc.

outputTextBox.Text = GetInformation( fileName );

// obtain file/directory list of specified directory

directoryList = Directory.GetDirectories( fileName );

outputTextBox.Text +=

"\r\n\r\nDirectory contents:\r\n";

// output directoryList contents

for ( int i = 0; i <>

outputTextBox.Text += directoryList[ i ] + "\r\n";

}

else

{

// notify user that neither file nor directory exists

MessageBox.Show( inputTextBox.Text +

" does not exist", "File Error",

MessageBoxButtons.OK, MessageBoxIcon.Error );

}

} // end if

} // end method inputTextBox_KeyDown

// get information on file or directory

private string GetInformation( string fileName )

{

// output that file or directory exists

string information = fileName + " exists\r\n\r\n";

// output when file or directory was created

information += "Created: " +

File.GetCreationTime( fileName ) + "\r\n";

// output when file or directory was last modified

information += "Last modified: " +

File.GetLastWriteTime( fileName ) + "\r\n";

// output when file or directory was last accessed

information += "Last accessed: " +

File.GetLastAccessTime( fileName ) + "\r\n" + "\r\n";

return information;

} // end method GetInformation

} // end class FileTestForm

5. Creación de un archivo de texto de acceso secuencial

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

public class BankUIForm : System.Windows.Forms.Form

{

private System.ComponentModel.Container components = null;

public System.Windows.Forms.Label accountLabel;

public System.Windows.Forms.TextBox accountTextBox;

public System.Windows.Forms.Label firstNameLabel;

public System.Windows.Forms.TextBox firstNameTextBox;

public System.Windows.Forms.Label lastNameLabel;

public System.Windows.Forms.TextBox lastNameTextBox;

public System.Windows.Forms.Label balanceLabel;

public System.Windows.Forms.TextBox balanceTextBox;

// number of TextBoxes on Form'

protected int TextBoxCount = 4;

// enumeration constants specify TextBox indices

public enum TextBoxIndices

{

ACCOUNT,

FIRST,

LAST,

BALANCE

} // end enum

[STAThread]

static void Main()

{

Application.Run( new BankUIForm() );

}

// Visual Studio .NET generated code

// clear all TextBoxes

public void ClearTextBoxes()

{

// iterate through every Control on form

for ( int i = 0; i <>

{

Control myControl = Controls[ i ]; // get control

// determine whether Control is TextBox

if ( myControl is TextBox )

{

// clear Text property (set to empty strng)

myControl.Text = "";

}

}

} // end method ClearTextBoxes

// set text box values to string array values

public void SetTextBoxValues( string[] values )

{

// determine whether string array has correct length

if ( values.Length != TextBoxCount )

{

// throw exception if not correct length

throw( new ArgumentException( "There must be " +

(TextBoxCount + 1) + " strings in the array" ) );

}

// set array values if array has correct length

else

{

// set array values to text box values

accountTextBox.Text =

values[ ( int )TextBoxIndices.ACCOUNT ];

firstNameTextBox.Text =

values[ ( int )TextBoxIndices.FIRST ];

lastNameTextBox.Text =

values[ ( int )TextBoxIndices.LAST ];

balanceTextBox.Text =

values[ ( int )TextBoxIndices.BALANCE ];

}

} // end method SetTextBoxValues

// return text box values as string array

public string[] GetTextBoxValues()

{

string[] values = new string[ TextBoxCount ];

// copy text box fields to string array

values[ ( int )TextBoxIndices.ACCOUNT ] =

accountTextBox.Text;

values[ ( int )TextBoxIndices.FIRST ] =

firstNameTextBox.Text;

values[ ( int )TextBoxIndices.LAST ] =

lastNameTextBox.Text;

values[ ( int )TextBoxIndices.BALANCE ] =

balanceTextBox.Text;

return values;

} // end method GetTextBoxValues

} // end class BankUIForm

6. Lectura de datos desde un archive de texto de acceso secuencial

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

using System.Runtime.Serialization;

// Deitel namespaces

using BankLibrary;

public class ReadSequentialAccessFileForm : BankUIForm

{

System.Windows.Forms.Button openButton;

System.Windows.Forms.Button nextButton;

private System.ComponentModel.Container components = null;

// stream through which serializable data are read from file

private FileStream input;

// object for deserializing Record in binary format

private BinaryFormatter reader = new BinaryFormatter();

[STAThread]

static void Main()

{

Application.Run( new ReadSequentialAccessFileForm() );

}

// Visual Studio .NET generated code

// invoked when user clicks Open button

private void openButton_Click(

object sender, System.EventArgs e )

{

// create dialog box enabling user to open file

OpenFileDialog fileChooser = new OpenFileDialog();

DialogResult result = fileChooser.ShowDialog();

string fileName; // name of file containing data

// exit event handler if user clicked Cancel

if ( result == DialogResult.Cancel )

return;

// get specified file name

fileName = fileChooser.FileName;

ClearTextBoxes();

// show error if user specified invalid file

if ( fileName == "" || fileName == null )

MessageBox.Show( "Invalid File Name", "Error",

MessageBoxButtons.OK, MessageBoxIcon.Error );

else

{

// create FileStream to obtain read access to file

input = new FileStream( fileName, FileMode.Open,

FileAccess.Read );

// enable next record button

nextButton.Enabled = true;

}

} // end method openButton_Click

// invoked when user clicks Next button

private void nextButton_Click(

object sender, System.EventArgs e )

{

// deserialize Record and store data in TextBoxes

try

{

// get next Record available in file

Record record =

( Record )reader.Deserialize( input );

// store Record values in temporary string array

string[] values = new string[] {

record.Account.ToString(),

record.FirstName.ToString(),

record.LastName.ToString(),

record.Balance.ToString() };

// copy string array values to TextBox values

SetTextBoxValues( values );

}

// handle exception when no Records in file

catch( SerializationException )

{\

// close FileStream if no Records in file

input.Close();

// enable Open Record button

openButton.Enabled = true;

// disable Next Record button

nextButton.Enabled = false;

ClearTextBoxes();

// notify user if no Records in file

MessageBox.Show( "No more records in file", "",

MessageBoxButtons.OK, MessageBoxIcon.Information );

}

} // end method nextButton_Click

} // end class ReadSequentialAccessFileForm

7. Serialización

Un objeto serializado, se representa como una secuencia de bytes que incluye los datos de ese objeto, así como información acerca del tipo del objeto y los tipos de los datos almacenados en ese objeto. Una vez que se escribe un objeto serializado en un archivo, puede leerse desde ese archivo y deserializarse; esto es, la información sobre el tipo y los bytes que representan al objeto y sus datos pueden usarse para recrear al objeto en la memoria.