Professional Documents
Culture Documents
See Also
The “FileVersionInfo Class” topic in the MSDN documentation.
Solution
Use the various properties in the DriveInfo class as shown here:
public static void DisplayAllDriveInfo( )
{
foreach (DriveInfo drive in DriveInfo.GetDrives( ))
{
if (drive.IsReady)
{
Console.WriteLine("Drive " + drive.Name + " is ready.");
Console.WriteLine("AvailableFreeSpace: " + drive.AvailableFreeSpace);
Console.WriteLine("DriveFormat: " + drive.DriveFormat);
Console.WriteLine("DriveType: " + drive.DriveType);
Console.WriteLine("Name: " + drive.Name);
Console.WriteLine("RootDirectory.FullName: " +
drive.RootDirectory.FullName);
Console.WriteLine("TotalFreeSpace: " + drive.TotalFreeSpace);
Console.WriteLine("TotalSize: " + drive.TotalSize);
Console.WriteLine("VolumeLabel: " + drive.VolumeLabel);
}
else
{
Console.WriteLine("Drive " + drive.Name + " is not ready.");
}
}
}
Discussion
To make sure your data is safe, you need to close the MemoryStream and CryptoStream
objects as soon as possible, as well as calling Dispose on the ICryptoTransform imple-
mentation to clear out any resources used in this encryption. The using statement
makes this process much easier, makes your code easier to read, and leads to fewer
programming mistakes.
See Also
The “SymmetricAlgorithm.Clear Method” and “AsymmetricAlgorithm.Clear
Method” topics in the MSDN documentation.
Preface | xxi
Discussion
The CompressFile method accepts a path to the source file to compress, a path to the
destination of the compressed file, and a CompressionType enumeration value indicat-
ing which type of compression algorithm to use (Deflate or GZip). This method pro-
duces a file containing the compressed data.
The DecompressFile method accepts a path to the source compressed file to decom-
press, a path to the destination of the decompressed file, and a CompressionType enu-
meration value indicating which type of decompression algorithm to use (Deflate or
GZip).
The TestCompressNewFile method shown in Example 12-6 exercises the CompressFile
and DecompressFile methods defined in the Solution section of this recipe.
FileStream fs =
new FileStream(@"C:\NewNormalFile.txt",
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
using(fs)
{
fs.Write(data,0,data.Length);
}
CompressFile(@"C:\NewNormalFile.txt", @"C:\NewCompressedFile.txt",
CompressionType.Deflate);
DecompressFile(@"C:\NewCompressedFile.txt", @"C:\NewDecompressedFile.txt",
CompressionType.Deflate);
CompressFile(@"C:\NewNormalFile.txt", @"C:\NewGZCompressedFile.txt",
CompressionType.GZip);
DecompressFile(@"C:\NewGZCompressedFile.txt", @"C:\NewGZDecompressedFile.txt",
CompressionType.GZip);
/// <summary>
/// ToString override to provide class detail
/// </summary>
/// <returns>formatted string with class details</returns>
public override string ToString( )
{
return "There are " + FixedSizeCollection<T>.InstanceCount.ToString( ) +
" instances of " + this.GetType( ).ToString( ) +
" and this instance contains " + this.ItemCount + " items...";
}
}
Things start to get a little different with FixedSizeCollection<T> when you look at
the Items array property implementation. The Items array is declared as:
private T[] Items { get; set; }
instead of:
private object[] Items { get; set; }
The Items array property uses the type parameter of the generic class (<T>) to deter-
mine what type of items are allowed. FixedSizeCollection uses object for the Items
array property type, which allows any type to be stored in the array of items (since all
types are convertible to object), while FixedSizeCollection<T> provides type safety
by allowing the type parameter to dictate what types of objects are permitted. Notice
also that the properties have no associated private backing field declared for storing
the array. This is an example of using the new Automatically Implemented Proper-
ties in C# 3.0. Under the covers, the C# compiler is creating a storage element of the
type of the property, but you don’t have to write the code for the property storage
anymore if you don’t have specific code that has to execute when accessing the prop-
erties. To make the property read-only, simply mark the set; declaration private.
The next difference is visible in the method declarations of AddItem and GetItem.
AddItem now takes a parameter of type T, whereas in FixedSizeCollection, it took a
parameter of type object. GetItem now returns a value of type T, whereas in
FixedSizeCollection, it returned a value of type object. These changes allow the
methods in FixedSizeCollection<T> to use the instantiated type to store and retrieve
the items in the array, instead of having to allow any object to be stored as in
FixedSizeCollection:
/// <summary>
/// Add an item to the class whose type
/// is determined by the instantiating type
/// </summary>
/// <param name="item">item to add</param>
/// <returns>the zero-based index of the item added</returns>
public int AddItem(T item)
See Also
The “XElement Class,” “XCData Class,” “XmlDocument Class,” “XmlWriter Class,”
“XmlElement Class,” and “CDATA Sections” topics in the MSDN documentation.
Solution
The solution for this is to use LINQ to XML to perform a transformation in C#. In
the example code, you transform some personnel data from a fictitious business
stored in Personnel.xml. The data is first transformed into HTML, and then into
comma-delimited format:
// LINQ way
XElement personnelData = XElement.Load(@"..\..\Personnel.xml");
// Create HTML
XElement personnelHtml =
new XElement("html",
new XElement("head"),
new XElement("body",
new XAttribute("title","Personnel"),
new XElement("p",
new XElement("table",
new XAttribute("border","1"),
Discussion
The static Convert.ToInt32 method has an overload that takes a string containing a
number and an integer defining the base of this number. This method then converts
the numeric string into an integer, Console.WriteLine, and then converts the num-
ber to base10 and displays it.
The other static methods of the Convert class, such as ToByte, ToInt64, and ToInt16,
also have this same overload, which accepts a number as a string and the base in
which this number is expressed. Unfortunately, these methods convert from a string
value expressed in base2, base8, base10, and base16 only. They do not allow for con-
verting a value to a string expressed in any other base types than base10. However,
the ToString methods on the various numeric types do allow for this conversion.
See Also
The “Convert Class” and “Converting with System.Convert” topics in the MSDN
documentation.
Solution
Use the static TryParse method of any of the numeric types. For example, to deter-
mine whether a string contains a double, use the following method:
string str = "12.5";
double result = 0;
if(double.TryParse(str,
System.Globalization.NumberStyles.Float,
System.Globalization.NumberFormatInfo.CurrentInfo,
out result))
See Also
The “TcpClient Class,” “NetworkStream Class,” and “Encoding.ASCII Property”
topics in the MSDN documentation.
Solution
Use the System.Net.WebClient class to send a set of name-value pairs to the web
server using the UploadValues method. This class enables you to masquerade as the
browser executing a form by setting up the name-value pairs with the input data.
The input field ID is the name, and the value to use in the field is the value:
using System;
using System.Net;
using System.Text;
using System.Collections.Specialized;
// In order to use this, you need to run the CSCBWeb project first.
Uri uri = new Uri("http://localhost:7472/CSCBWeb/WebForm1.aspx");
WebClient client = new WebClient( );