|
More than any other assignment, file processing is in prime
need of exception handling. During file
processing, there are many things that can go wrong. For this reason, the
creation and/or management of streams should be performed in a try block
to get ready to handle exceptions that would occur. Besides actually handling
exceptions, you can use the finally
keyword to free resources.
The finally keyword is used to create a section of an
exception. Like catch, a finally block cannot exist by itself. It can be created
following a try section. The formula used would be:
try
{
}
finally
{
}
Based on this:
- The finally section has a body of its
own, delimited by its curly brackets
- Like catch, the finally section is
created after the try section
- Unlike catch, finally never
has parentheses and never takes arguments
- Unlike catch, the finally
section is always executed
Because the finally clause always gets
executed, you can include any type of code in it but it is usually appropriate
to free the resources that were allocated such as those used during streaming. Here is an example:
System::Void btnSave_Click(System::Object^ sender, System::EventArgs^ e)
{
String ^ NameOfFile = L"Persons.spr";
FileStream ^ fstPersons = gcnew FileStream(NameOfFile,
FileMode::Create);
BinaryWriter ^ wrtPersons = gcnew BinaryWriter(fstPersons);
try {
wrtPersons->Write(txtPerson1->Text);
wrtPersons->Write(txtPerson2->Text);
wrtPersons->Write(txtPerson3->Text);
wrtPersons->Write(txtPerson4->Text);
}
finally
{
wrtPersons->Close();
fstPersons->Close();
}
txtPerson1->Text = L"";
txtPerson2->Text = L"";
txtPerson3->Text = L"";
txtPerson4->Text = L"";
}
In the same way, you can use a finally section to free
resources used when reading from a stream. Of course, since the whole block of code starts with a try
section, it is used for exception handling. This means that you can add the
necessary and appropriate catch section(s) but you don't have to.
|
Practical
Learning: Finally Releasing Resources
|
|
- Start Microsoft Visual C++/CLI or Visual Studio and create a Windows Forms Application named
ClarksvilleIceCream2
- In the Properties window, change the form's Text to Ice
Cream Vending Machine
- In the Common Controls section of the Toolbox, click ToolTip and
click the form
- In the Menu and Toolbars section of the Toolbox, click StatusStrip
and click the form
- Design the form as follows:
 |
| Control |
Name |
Text |
ToolTip on toolTip1 |
Additional Properties |
| GroupBox |
|
|
|
|
| Label |
|
Please enter your initials and click Open: |
|
|
| TextTox |
txtInitials |
|
First enter your initials. Then click Open |
|
| Button |
btnFileProcessing |
Open |
First enter your initials. Then click Open |
|
| Label |
|
Order Date: |
|
|
| DateTimePicker |
dtpOrderDate |
|
Click the arrow to select a date |
Format: Short |
| Label |
|
Order Time: |
|
|
| DateTimePicker |
dtpOrderTime |
|
Click each section, then click one of the arrows to change its value |
Format: Time
ShowUpDown: True |
| Label |
|
Flavor: |
|
|
| ComboBox |
cboFlavors |
|
Click the arrow to display a list, then select a flavor from the list |
DropDownStyle: DropDownList |
| Label |
|
Container: |
|
|
| ComboBox |
cboContainers |
|
Click to display the list of containers and select one |
DropDownStyle: DropDownList |
| Label |
|
Ingredient: |
|
|
| ComboBox |
cboIngredients |
|
Display the list of ingredients and make the customer's choice |
DropDownStyle: DropDownList |
| Label |
|
Scoops: |
|
|
| TextBox |
txtScoops |
1 |
Enter the number of scoops (1, 2, or 3) to fill the container |
TextAlign: Right |
| Label |
|
Order Total: |
|
|
| TextBox |
txtOrderTotal |
0.00 |
This displays the total amount of this order |
TextAlign: Right |
| Label |
|
Amount Tended: |
|
|
| TextBox |
txtAmountTended |
|
Amount you inserted into the machine |
|
| Label |
|
Change |
|
|
| TextBox |
txtChange |
|
Amount given back to you |
|
| Button |
btnClose |
Close |
Click to end |
|
|
- Click the combo box to the right of the Flavor label. Then, in the
Properties, click the ellipsis button
of Items property and create the list with:
Vanilla
Cream of Cocoa
Chocolate Chip
Cherry Coke
Butter Pecan
Chocolate Cookie
Chunky Butter
Organic Strawberry
Chocolate Brownies
Caramel Au Lait |
- Click OK
- Click the combo box to the right of the Container label. Then, in
the Properties, click the ellipsis button
of Items property and create the list with:
- Click OK
- Click the combo box to the right of the Ingredient label. Then, in
the Properties, click the ellipsis button
of Items property and create the list with:
None
Peanuts
Mixed Nuts
M & M
Cookies |
- Click OK
- To add a new form to the project, on the main menu, click Project
-> Add Class...
- In the Templates section, click Windows Form and set the Name to FileProcessing
- Click Add and design the form as follows:
 |
| Control |
Name |
Text |
Other Properties |
| Label |
lblMessage |
Message: |
Modifiers: Public |
| TextBox |
txtInitials |
|
Modifiers: Public |
| Button |
btnFileProcessing |
Process |
DialogResult: OK
Modifiers: Public |
|
- Return to the first form
- Double-click outside of any control, such as to the left side of the group
box to generate the Load event of the form
- Implement the form's Load event as follows:
System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
Initials = L"";
FileStream ^ stmIceCream = nullptr;
BinaryReader ^ bnrIceCream = nullptr;
FileProcessing ^ frmFileProcessing = gcnew FileProcessing;
frmFileProcessing->lblMessage->Text = L"Enter your initials and click Open";
frmFileProcessing->btnFileProcessing->Text = L"Open";
frmFileProcessing->txtInitials->Text = L"";
frmFileProcessing->txtInitials->Focus();
if( frmFileProcessing->ShowDialog() ==
System::Windows::Forms::DialogResult::OK )
{
Initials = frmFileProcessing->txtInitials->Text;
String ^ NameOfFile = frmFileProcessing->txtInitials->Text + L".icr";
String ^ OrderDate;
String ^ OrderTime;
String ^ SelectedFlavor;
String ^ SelectedContainer;
String ^ SelectedIngredient;
int Scoops;
double OrderTotal;
stmIceCream = gcnew FileStream(NameOfFile, FileMode::Open);
bnrIceCream = gcnew BinaryReader(stmIceCream);
try {
OrderDate = bnrIceCream->ReadString();
OrderTime = bnrIceCream->ReadString();
SelectedFlavor = bnrIceCream->ReadString();
SelectedContainer = bnrIceCream->ReadString();
SelectedIngredient = bnrIceCream->ReadString();
Scoops = bnrIceCream->ReadInt32();
OrderTotal = bnrIceCream->ReadDouble();
dtpOrderDate->Value = DateTime::Parse(OrderDate);
dtpOrderTime->Value = DateTime::Parse(OrderTime);
cboFlavors->Text = SelectedFlavor;
cboContainers->Text = SelectedContainer;
cboIngredients->Text = SelectedIngredient;
txtScoops->Text = Scoops.ToString();
txtOrderTotal->Text = OrderTotal.ToString(L"F");
}
finally
{
bnrIceCream->Close();
stmIceCream->Close();
}
}
}
|
- Execute the application and test it.
- On the form, click the Scoops text box and click the Events button
of the Properties window
- In the Events section of the Properties window, look for and
double-click Leave to generate its event
- Implement it as follows:
System::Void txtScoops_Leave(System::Object^ sender, System::EventArgs^ e)
{
double PriceContainer = 0.00,
PriceIngredient = 0.00,
PriceScoops = 0.00,
OrderTotal = 0.00;
int NumberOfScoops = 1;
// The price of a container depends on which one the customer selected
if( cboContainers->Text == L"Cone" )
PriceContainer = 0.55;
else if( cboContainers->Text == L"Cup" )
PriceContainer = 0.75;
else
PriceContainer = 1.15;
// Find out if the customer wants any ingredient at all
if( this->cboIngredients->Text == L"None" )
PriceIngredient = 0.00;
else
PriceIngredient = 0.95;
try {
// Get the number of scoops
NumberOfScoops = int::Parse(this->txtScoops->Text);
if( NumberOfScoops == 1 )
PriceScoops = 1.85;
else if( NumberOfScoops == 2 )
PriceScoops = 2.55;
else // if( NumberOfScoops == 3 )
PriceScoops = 3.25;
// Make sure the user selected a flavor,
// otherwise, there is no reason to process an order
if( this->cboFlavors->Text != L"" )
{
OrderTotal = PriceScoops + PriceContainer + PriceIngredient;
this->txtOrderTotal->Text = OrderTotal.ToString("F");
txtAmountEntered->Text = OrderTotal.ToString("F");
txtAmountEntered->Focus();
System::Windows::FormsDialogResult answer =
MessageBox::Show(
L"Do you want to save this order to remember it "
L"the next time you come to "
L"get your ice scream?",
L"Ice Cream Vending Machine",
MessageBoxButtons::YesNo,
MessageBoxIcon::Question);
if( answer == System::Windows::Forms::DialogResult::Yes )
{
MessageBox::Show(
L"Please enter your initials and click Save");
btnFileProcessing->Text = L"Save";
txtInitials->Text = L"";
txtInitials->Focus();
}
}
}
catch(FormatException ^)
{
MessageBox::Show(L"The value you entered for the scoops is not valid"
L"\nOnly natural numbers such as 1, 2, or 3 are allowed"
L"\nPlease try again");
}
}
|
- Return to the form
- On the form, click the Amount Entered text box and, in the Events
section of the Properties window, generate the Leave event
- Implement it as follows:
System::Void txtAmountEntered_Leave(System::Object^ sender, System::EventArgs^ e)
{
double TotalOrder,
AmountEntered = 0.00,
Change;
// Get the value of the total order. Actually, this value
// will be provided by the main form
TotalOrder = double::Parse(this->txtOrderTotal->Text);
try
{
// The amount tended will be entered by the user
AmountEntered = double::Parse(this->txtAmountEntered->Text);
}
catch(FormatException ^)
{
MessageBox::Show(L"The amount you entered is not "
L"valid - Please try again!");
}
// Calculate the difference of both values, assuming
// that the amount tended is higher
Change = AmountEntered - TotalOrder;
// Display the result in the Difference text box
this->txtChange->Text = Change.ToString("F");
}
|
- Scroll up in the file and type the following:
#pragma once
#include "FileProcessing.h"
namespace IceCream2 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
/// <summary>
/// Summary for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
/// </summary>
public ref class Form1 : public System::Windows::Forms::Form
{
. . . No Change
private: System::ComponentModel::IContainer^ components;
String ^ Initials;
private:
/// <summary>
/// Required designer variable.
/// </summary>
}
};
}
|
- Return to the form
- Double-click the Close button and implement its Click event as
follows:
System::Void btnClose_Click(System::Object^ sender, System::EventArgs^ e)
{
FileStream ^ stmIceCream = nullptr;
BinaryWriter ^ bnwIceCream = nullptr;
System::Windows::Forms::DialogResult answer =
MessageBox::Show(L"Do you want to save this order to remember it "
L"the next time you come to "
L"get your ice scream?",
L"Ice Cream Vending Machine",
MessageBoxButtons::YesNo,
MessageBoxIcon::Question);
if( answer == System::Windows::Forms::DialogResult::Yes )
{
MessageBox::Show(L"In the following form, please enter "
L"your initials and click Save");
FileProcessing ^ frmFileProcessing = gcnew FileProcessing;
frmFileProcessing->lblMessage->Text = "Enter your initials and click Save";
frmFileProcessing->btnFileProcessing->Text = L"Save";
frmFileProcessing->txtInitials->Text = Initials;
frmFileProcessing->txtInitials->Focus();
if( frmFileProcessing->ShowDialog() ==
System::Windows::Forms::DialogResult::OK )
{
if( frmFileProcessing->txtInitials->Text == L"" )
MessageBox::Show(L"Invalid File Name: Empty Initials");
else
{
String ^ NameOfFile = frmFileProcessing->txtInitials->Text + L".icr";
try {
stmIceCream = gcnew FileStream(NameOfFile, FileMode::Create);
bnwIceCream = gcnew BinaryWriter(stmIceCream);
int Scoops = int::Parse(txtScoops->Text);
double OrderTotal = double::Parse(txtOrderTotal->Text);
bnwIceCream->Write(dtpOrderDate->Value.ToShortDateString());
bnwIceCream->Write(dtpOrderTime->Value.ToShortTimeString());
bnwIceCream->Write(cboFlavors->Text);
bnwIceCream->Write(cboContainers->Text);
bnwIceCream->Write(cboIngredients->Text);
bnwIceCream->Write(Scoops);
bnwIceCream->Write(OrderTotal);
}
finally
{
bnwIceCream->Close();
stmIceCream->Close();
}
MessageBox::Show(L"The order has been saved");
}
}
}
else
MessageBox::Show("Good Bye: It was a delight serving you");
Close();
}
|
- Execute the application and test it
- Close the form
|
.NET Framework Exception Handling for File Processing
|
|
In the previous lesson of our introduction to file
processing, we behaved as if everything was alright. Unfortunately, file
processing can be very strict in its assignments. Fortunately, the .NET
Framework provides various Exception-oriented classes to deal with almost any
type of exception you can think of.
One of the most important aspects of file processing is the
name of the file that will be dealt with. In some cases you can provide this
name to the application or document. In some other cases, you would let the user
specify the name of the path. Regardless of how the name of the file would be
provided to the operating system, when this name is acted upon, the compiler
will be
asked to work on the file. If the file doesn't exist, the operation cannot be
carried. Furthermore, the compiler would throw an error. There are many other
exceptions that can be thrown as a result of something going bad during file
processing:
FileNotFoundException: The exception thrown when a
file has not been found is of type FileNotFoundException. Here is an example
of handling it:
using namespace System;
using namespace System::IO;
int main()
{
/* String ^ NameOfFile = L"Members.clb";
FileStream ^ fstPersons = gcnew FileStream(NameOfFile, FileMode::Create);
BinaryWriter ^ wrtPersons = gcnew BinaryWriter(fstPersons);
try
{
wrtPersons->Write(L"James Bloch");
wrtPersons->Write(L"Catherina Wallace");
wrtPersons->Write(L"Bruce Lamont");
wrtPersons->Write(L"Douglas Truth");
}
finally
{
wrtPersons->Close();
fstPersons->Close();
}*/
String ^ NameOfFile = L"Members.clc";
String ^ strLine = L"";
try {
FileStream ^ fstMembers =
gcnew FileStream(NameOfFile, FileMode::Open);
BinaryReader ^ rdrMembers = gcnew BinaryReader(fstMembers);
try {
strLine = rdrMembers->ReadString();
Console::WriteLine(strLine);
strLine = rdrMembers->ReadString();
Console::WriteLine(strLine);
strLine = rdrMembers->ReadString();
Console::WriteLine(strLine);
strLine = rdrMembers->ReadString();
Console::WriteLine(strLine);
}
finally
{
rdrMembers->Close();
fstMembers->Close();
}
}
catch (FileNotFoundException ^ ex)
{
Console::Write(L"Error: " + ex->Message);
Console::WriteLine(L" May be the file doesn't exist " +
L"or you typed it wrong!");
}
return 0;
}
Here is an example of what this would produce:
Error: Could not find file 'c:\Documents and Settings\Administrator
\My Documents\Visual Studio 2005\Projects\FileProcessing2
\FileProcessing2\Members.clc'. May be the file doesn't exist
or you typed it wrong!
Press any key to continue . . .
IOException: As mentioned already, during file
processing, anything could go wrong. If you don't know what caused an error, you
can throw the IOException exception.
|
Practical
Learning: Handling File Processing Exceptions
|
|
- In the Scopes combo box, select IceCream1::Form1 and, in the Functions combo box, select
Form1_Load
- To throw a FileNotFoundException exception, change the event as follows:
System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
Initials = L"";
FileStream ^ stmIceCream = nullptr;
BinaryReader ^ bnrIceCream = nullptr;
FileProcessing ^ frmFileProcessing = gcnew FileProcessing;
frmFileProcessing->lblMessage->Text = L"Enter your initials and click Open";
frmFileProcessing->btnFileProcessing->Text = L"Open";
frmFileProcessing->txtInitials->Text = L"";
frmFileProcessing->txtInitials->Focus();
if( frmFileProcessing->ShowDialog() ==
System::Windows::Forms::DialogResult::OK )
{
Initials = frmFileProcessing->txtInitials->Text;
String ^ NameOfFile = frmFileProcessing->txtInitials->Text + L".icr";
try {
stmIceCream = gcnew FileStream(NameOfFile, FileMode::Open);
bnrIceCream = gcnew BinaryReader(stmIceCream);
try {
String ^ OrderDate;
String ^ OrderTime;
String ^ SelectedFlavor;
String ^ SelectedContainer;
String ^ SelectedIngredient;
int Scoops;
double OrderTotal;
OrderDate = bnrIceCream->ReadString();
OrderTime = bnrIceCream->ReadString();
SelectedFlavor = bnrIceCream->ReadString();
SelectedContainer = bnrIceCream->ReadString();
SelectedIngredient = bnrIceCream->ReadString();
Scoops = bnrIceCream->ReadInt32();
OrderTotal = bnrIceCream->ReadDouble();
dtpOrderDate->Value = DateTime::Parse(OrderDate);
dtpOrderTime->Value = DateTime::Parse(OrderTime);
cboFlavors->Text = SelectedFlavor;
cboContainers->Text = SelectedContainer;
cboIngredients->Text = SelectedIngredient;
txtScoops->Text = Scoops.ToString();
txtOrderTotal->Text = OrderTotal.ToString(L"F");
}
finally
{
bnrIceCream->Close();
stmIceCream->Close();
}
}
catch(FileNotFoundException ^)
{
MessageBox::Show(L"It looks like you have not previously "
L"ordered an ice cream here");
}
}
}
|
- Exercise the application and test it
- Close the form
In its high level of support for file processing, the .NET
Framework provides the FileInfo class. This class is equipped to handle
all types of file-related operations including creating, copying, moving,
renaming, or deleting a file. FileInfo is based on the FileSystemInfo
class that provides information on characteristics of a file.
|
Practical
Learning: Introducing File Information
|
|
- To start a new application, on the main menu, click File -> New
-> Project
- In the Templates list, click Windows Forms Application
- Set the name to WattsALoan1
- In the Properties window, change the form's Text to Watts
A Loan
- To be able to use the Visual Basic library, in the Solution
Explorer, right-click WattsALoan1 and click References...
- Click Add New Reference...
- In the .NET property page, click Microsoft.VisualBasic
- Click OK and OK
- In the Common Controls section of the Toolbox, click ToolTip and
click the form
- Design the form as follows:
 |
| Control |
Name |
Text |
ToolTip on toolTip1 |
| Label |
|
Acnt #: |
|
| Label |
|
Customer Name: |
|
| Label |
|
Customer: |
|
| TextBox |
txtAccountNumber |
|
Account number of the customer requesting
the loan |
| TextBox |
txtCustomerName |
|
Name of the customer requesting the loan |
| Label |
|
Empl #: |
|
| Label |
|
Employee Name: |
|
| Label |
|
Prepared By: |
|
| TextBox |
txtEmployeeNumber |
|
Employee number of the clerk preparing the
loan |
| TextBox |
txtEmployeeName |
|
Name of the clerk preparing the loan |
| Button |
btnNewEmployee |
|
Used to add a new employee to the company |
| Label |
|
Loan Amount: |
|
| TextBox |
txtLoanAmount |
|
Amount of loan the customer is requesting |
| Label |
|
Interest Rate: |
|
| TextBox |
txtInterestRate |
|
Annual percentage rate of the loan |
| Label |
|
% |
|
| Label |
|
Periods |
|
| TextBox |
|
txtPeriods |
The number of months the loan is supposed
to last |
| Button |
btnCalculate |
Calculate |
Used to calculate the monthly payment |
| Label |
|
Monthly Payment: |
|
| TextBox |
txtMonthlyPayment |
|
The minimum amount the customer should pay
every month |
| Button |
btnClose |
Close |
Used to close the form |
|
- Double-click the Calculate button and implement its event as
follows:
System::Void btnCalculate_Click(System::Object^ sender, System::EventArgs^ e)
{
double LoanAmount, InterestRate, Periods, MonthlyPayment;
try {
LoanAmount = double::Parse(txtLoanAmount->Text);
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid Loan Amount");
}
try {
InterestRate = double::Parse(txtInterestRate->Text);
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid Interest Rate");
}
try {
Periods = double::Parse(txtPeriods->Text);
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid Periods Value");
}
try {
MonthlyPayment =
Microsoft::VisualBasic::Financial::Pmt(InterestRate / 12 / 100,
Periods,
-LoanAmount,
0 ,
Microsoft::VisualBasic::DueDate::BegOfPeriod);
txtMonthlyPayment->Text = MonthlyPayment.ToString(L"C");
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid Periods Value");
}
}
|
- Return to the form and double-click the Close button to implement
its event as follows:
System::Void btnClose_Click(System::Object^ sender, System::EventArgs^ e)
{
Close();
}
|
- Return to the form
The FileInfo class is equipped with one constructor
whose syntax is:
public:
FileInfo(String ^ fileName);
This constructor takes as argument the name of a file or its
complete path. If you provide only the name of the file, the compiler would consider
the same directory of its project. Here is an example:
FileInfo ^ fleMembers = gcnew FileInfo(L"First.txt");
Alternatively, if you want, you can provide any valid
directory you have access to. In this case, you should provide the complete
path.
|
Practical
Learning: Initializing a File
|
|
- Double-click an unoccupied area on the body form
- Scroll up completely and, under the other using lines, type using
namespace System::IO
- Scroll down complement and change the Load event of the form as follows:
System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
String ^ strFilename = L"Employees.wal";
FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
}
|
- Save the file
The FileInfo constructor is mostly meant only to
indicate that you want to use a file, whether it exists already or it would be
created. Based on this, if you execute an application that has only a FileInfo
object created using the constructor as done above, nothing would happen.
To create a file, you have various alternatives. If you want
to create one without writing anything in it, which implies creating an empty file,
you can call the FileInfo::Create() method. Its syntax is:
public:
FileStream ^ Create();
This method simply creates an empty file. Here is an example
of calling it:
FileInfo ^ fleMembers = gcnew FileInfo(L"First.txt");
fleMembers->Create();
The FileInfo::Create() method returns a FileStream
object. You can use this returned value to write any type of value into the
file, including text. If you want to create a file that contains text, an
alternative is to call the FileInfo::CreateText() method. Its syntax is: public:
StreamWriter CreateText();
This method directly returns a StreamWriter
object. You can use this returned object to write text to the file.
When you call the FileInfo::Create() or the FileInfo::CreateText()
method, if the file passed as argument, or as the file in the path of the
argument, exists already, it would be deleted and a new one would be created with
the same name. This can cause the right file to be deleted. Therefore, before
creating a file, you may need to check whether it exists already. To do this,
you can check the value of the Boolean FileInfo::Exists property. This
property holds a true value if the file exists already and it holds a false
value if the file doesn't exist or it doesn't exist in the path.
Here is an example of checking the existence of a file:
FileInfo ^ fleMembers = gcnew FileInfo(L"First.txt");
fleMembers->Create();
if( fleMembers.Exists == true )
return;
|
Practical
Learning: Creating a Text File
|
|
- Change the Load event of the form as follows:
System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
String ^ strFilename = L"Employees.wal";
FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
// If the employees file was not created already,
// then create it
if( !fiEmployees->Exists )
{
StreamWriter ^ stwEmployees = fiEmployees->CreateText();
}
}
|
- Save the file
As mentioned earlier, the FileInfo::Create() method
returns a FileStream object. You can use this to specify the type of
operation that would be allowed on the file.
To write normal text to a file, you can first call the FileInfo::CreateText()
method. This method returns a StreamWriter object. The StreamWriter
class is based on the TextWriter class that is equipped with the Write()
and the WriteLine() methods used to write values to a file. The Write()
method writes text on a line and keeps the caret on the same line. The WriteLine()
method writes a line of text and moves the caret to the next line.
After writing to a file, you should close the StreamWriter
object to free the resources it was using during its operation(s).
|
Practical
Learning: Writing to a Text File
|
|
- Change the Load event of the form as follows:
System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
String ^ strFilename = L"Employees.wal";
FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
// If the employees file was not created already,
// then create it
if( !fiEmployees->Exists )
{
StreamWriter ^ stwEmployees = fiEmployees->CreateText();
// And create a John Doe employee
try {
stwEmployees->WriteLine(L"00-000");
stwEmployees->WriteLine(L"John Doe");
}
finally
{
stwEmployees->Close();
}
}
}
|
- Save the file
You may have created a text-based file and written to
it. If you open such a file and find out that a piece of information is
missing, you can add that information to the end of the file. To do this,
you can call the FileInfo::AppenText() method. Its syntax is:
public:
StreamWriter ^ AppendText();
When calling this method, you can retrieve the StreamWriter
object that it returns, then use that object to add new information to the
file.
|
Practical
Learning: Writing to a Text File
|
|
- To create a new form, on the main menu, click Project -> Add New
Item...
- In the Templates list, click Windows Form
- Set the Name to NewEmployee and click Add
- Design the form as follows:
 |
| Control |
Text |
Name |
| Label |
Employee #: |
|
| TextBox |
|
txtEmployeeNumber |
| Label |
Employee Name: |
|
| TextBox |
|
txtEmployeeName |
| Button |
Create |
btnCreate |
| Button |
Close |
btnClose |
|
- Right-click the form and click View Code
- In the top section of the file, under the using using lines, type
using namespace System::IO;
- Return to the New Employee form and double-click the Create button
- Implement its event as follows:
System::Void btnCreate_Click(System::Object^ sender, System::EventArgs^ e)
{
String ^ strFilename = L"Employees.wal";
FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
StreamWriter ^ stwEmployees = nullptr;
// Normally, we should have the file already but just in case...
if( !fiEmployees->Exists )
stwEmployees = fiEmployees->CreateText();
else // If the file exists already, then we will only add to it
stwEmployees= fiEmployees->AppendText();
try {
stwEmployees->WriteLine(txtEmployeeNumber->Text);
stwEmployees->WriteLine(txtEmployeeName->Text);
}
finally
{
stwEmployees->Close();
}
txtEmployeeNumber->Text = L"";
txtEmployeeName->Text = L"";
txtEmployeeNumber->Focus();
}
|
- Return to the New Employee form and double-click the Close button
- Implement its event as follows:
System::Void btnClose_Click(System::Object^ sender, System::EventArgs^ e)
{
Close();
}
|
- Access the Form1 form
- Double-click the top New button
- In the top section of the file, under the #pragma once line, type
#include "NewEmployee.h"
- Scroll down and implement its Click event as follows:
System::Void btnNewEmployee_Click(System::Object^ sender, System::EventArgs^ e)
{
NewEmployee ^ frmNewEmployee = gcnew NewEmployee;
frmNewEmployee->ShowDialog();
}
|
- Return to the form
- In the combo box on top of the Properties window, select txtEmployeeNumber
- On the Properties window, click the Events button and double-click Leave
- Implement the event as follows:
System::Void txtEmployeeNumber_Leave(System::Object^ sender, System::EventArgs^ e)
{
String ^ strFilename = L"Employees.wal";
FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
if(fiEmployees->Exists )
{
if( txtEmployeeNumber->Text == L"" )
{
txtEmployeeName->Text = L"";
return;
}
else
{
StreamReader ^ strEmployees = fiEmployees->OpenText();
String ^ strEmployeeNumber, ^ strEmployeeName;
bool found = false;
try {
while( strEmployeeNumber = strEmployees->ReadLine() )
{
if( strEmployeeNumber == txtEmployeeNumber->Text )
{
strEmployeeName = strEmployees->ReadLine();
txtEmployeeName->Text = strEmployeeName;
found = true;
}
}
// When the application has finished checking the file
// if there was no employee with that number, let the user know
if( found == false )
{
MessageBox::Show(L"No employee with that number was found");
txtEmployeeName->Text = L"";
txtEmployeeNumber->Focus();
}
}
finally
{
strEmployees->Close();
}
}
}
}
|
- Execute the application to test it
- First create a few employees as follows:
| Employee # |
Employee Name |
| 42-806 |
Patricia Katts |
| 75-148 |
Helene Mukoko |
| 36-222 |
Frank Leandro |
| 42-808 |
Gertrude Monay |
- Process a loan

- Close the application
|
|