Beginning Visual C# Exercises - Chapter 20 Answers
1. The System.IO namespace contains all of the classes for reading and writing data to files.
2. The FileStream class maintains an internal file pointer allowing random file access via the
Seek() method. Also, the FileStream class exclusively handles raw byte data making it the
only handler for non-text files, such as image or sound.
3. The StreamReader class has four methods to pull character data from the input stream:
Peek() Returns the next available character but does not consume it
Read() Returns the next available character and advances the character position by one
ReadLine() Returns the current line and advances the character position to start of next line
ReadToEnd() Returns characters from the current position to the end of the stream as
a string
4. The FileSystemWatcher class exposes five events:
Changed raised when changes are made to the size, system attributes, last write time,
last access time, or security permissions
Created raised when a file or directory in the specified path is created
Deleted raised when a file or directory in the specified path is deleted
Renamed raised when a file or directory in the specified path is renamed
Error raised when the internal buffer overflows as a result of too many changes in a short time
5. Rewrite the "cmdWatch_Click()" event handler...
private void cmdWatch_Click(object sender, EventArgs e)
{
if (Watcher.EnableRaisingEvents == true)
{
//Stop watching
Watcher.EnableRaisingEvents = false;
lblWatch.Text = "";
txtLocation.Text = "";
cmdWatch.Enabled = false;
cmdWatch.Text = "Watch!";
}
else
{
Watcher.Path = Path.GetDirectoryName(txtLocation.Text);
Watcher.Filter = Path.GetFileName(txtLocation.Text);
Watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size;
lblWatch.Text = "Watching " + txtLocation.Text;
// Begin watching
Watcher.EnableRaisingEvents = true;
cmdWatch.Text = "Stop";
}
}
6. Declare the namespaces...
using System;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
In the Main() function...
// Specify SQL Server specific connection string
SqlConnection thisConnection = new
SqlConnection(@"Data Source=(local);Integrated Security=SSPI;Initial Catalog=northwind");
SqlDataAdapter thisAdapter = new
SqlDataAdapter("SELECT CustomerID, ContactName From Customers", thisConnection);
DataSet thisDataSet = new DataSet();
// Fill DataSet using query defined previously for DataAdapter
thisAdapter.Fill(thisDataSet, "Customers");
try
{
// Create a StreamWriter object
StreamWriter sw = new StreamWriter("customers.txt", false);
foreach (DataRow theRow in thisDataSet.Tables["Customers"].Rows)
{
// comma delimited fields
sw.WriteLine("{0},{1}", theRow["CustomerID"], theRow["ContactName"]);
}
// Write the file
sw.Close();
}
catch (IOException ex)
{
Console.WriteLine("An IO exception has been thrown!");
Console.WriteLine(ex.ToString());
Console.ReadLine();
return;
}
return;
|