Saturday, 10 February 2007

FileInfo.OpenRead vs FileInfo.OpenText

Essentially the definition of FileInfo.OpenRead & FileInfo.OpenText look similar, both opens the file with read-only access. The difference is FileInfo.OpenRead returns a FileStream & FileInfo.OpenText returns StreamReader object. This gives a slight difference when you interact with the file, lets first look at the OpenRead's FileStream object

using (FileStream fs = fi.OpenRead())
{
byte[] b = new byte[1024
];
UTF8Encoding temp
= new UTF8Encoding(true
);

while (fs.Read(b,0,b.Length) > 0
)
{
Console.WriteLine(temp.GetString(b));
}
}
The FileInfo.OpenText methods StreamReader code looks like the following:
// Open the stream and read it back.
using (StreamReader sr = File.OpenText(path))
{
string s = ""
;
while ((s = sr.ReadLine()) != null
)
{
Console.WriteLine(s);
}
}

I find the StreamReader makes it much easier to interact with the file.

Friday, 9 February 2007

FileStream vs File Class

The following lines of code create a file and add some text to the newly created file using the FileStream class.
string origString =
"I never saw an author who was aware that there is any "+
"dimensional difference between a fact and a surmise.\n"+
" - Mark Twain";

// create the file, write to it, save it.
FileStream fs = new FileStream("quote.txt", FileMode.Create);
fs.Write(ASCIIEncoding.ASCII.GetBytes(origString),
0, origString.Length);
fs.Close();
Compare this to the simpler code of the File class, which provides a series of static methods.

StreamWriter sw = File.CreateText("quote2.txt");
sw.Write(origString);
sw.Write(addString);
sw.Close();
 

High level overview of System.IO File & Directory classes

  • File (Static class that provides methods for testing for the existence of a file, copying files, deleting files, moving files, as well as opening of files and the creation of streams from files)
  • FileInfo (Instance class that provides information about a specific file. Also contains instance methods for performing copy, move, delete and relaled operations).
  • Directory (Static class that provides methods for determing the existence of directories, creating directories, etc).
  • DirectoryInfo (Provides instance methods for operating on a specific directory, including renaming, obtaining list of files within directory, etc).
  • Path (Utility class for parsing and building path strings).

Thursday, 8 February 2007

Event Handling

Events are a way to allow a class to send a signal indicating that an event of some importance has taken place. Events are created from delegates using the event keyword. First, you declare the delegate.


delegate void StateChangedDelegate(object sender, EventArgs e);
The event is then declared as a member of the class:
 
public event StateChangedDelegate OnStateChangedHandler;
protected virtual
OnStateChanged(EventArgs e)
{
if (OnStateChangedHandler != null
)
{
OnStateChangedHandler(
this
, e);
}
}
Finally the calling class can subscribe to the event:
otherClass.OnStateChanged += new StateChangedDelegate(OtherClass_StateChanged);

Saturday, 3 February 2007

DirectoryInfo Class

Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. This class is sealed and cannot be inherited.

If you are going to reuse an object several times, consider using the instance method of DirectoryInfo instead of the corresponding static methods of Directory class, because a security check will not always be necessary.

Common Properties
  • Parent (Gets the DirectoryInfo object for the parent directory of the current directory in the directory hierarchy).
  • Root (Gets the root part of the directory's path as a string).

Common Members

  • Create (Creates the directory described in the current DirectoryInfo object).
  • CreateSubdirectory (Creates a new directory as a child directory of the current directory in the directory hierarchy).
  • GetDirectories (Retrieves an array of DirectoryInfo objects that represent subdirectories of the current directory).
  • GetFiles (Retrieves an array of FileInfo objects that represent all the files in the current directory).
  • GetFileSystemInfos (Retrieves an array of FileSystemInfo objects that represent both files and subdirectories in the current directory).
  • MoveTo (Moves the current directory to a new location).

    //
    Specify the directories you want to manipulate.
    DirectoryInfo di = new DirectoryInfo(@"c:\MyDir");

    try

    {

    // Determine whether the directory exists.

    if (di.Exists)
    {
    // Indicate that the directory already exists.

    Console.WriteLine("That path exists already.");
    return
    ;
    }

    // Try to create the directory.

    di.Create();
    Console.WriteLine(
    "The directory was created successfully."
    );

    // Delete the directory.

    di.Delete();
    Console.WriteLine(
    "The directory was deleted successfully."
    );

FileInfo Class

The FileInfo class provides instance methods for the creation, copying, deletion, moving and opening of files, and aids in the creation of FileStream objects. The FileInfo class is a sealed class meaning you are unable to inherit from it.

Many of the FileInfo methods return other I/O types when you create or open files. You can use these other types to further manipulate a file.

If you are going to reuse an object several times, you should consider using the instance method of FileInfo instead of the corresponding static methods of the File class, because a security check will not always be necessary.

Common Members
  • FileInfo (Initialises a new instance of the FileInfo class, which acts a wrapper for a file path).
  • Attributes (Gets/Sets the FileAttributes of the current FileSystemInfo).
  • CreationTime (Gets/Sets the creation time of the current FileSystemInfo object).
  • Directory (Gets an instance of the parent directory).
  • DirectoryName (Gets a string representing the directories full path).
  • Exists (Gets a value indicating whether a file exists).
  • Extension (Gets the string representing the extension part of the file).

Common Methods

  • AppendText (Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo).
  • CopyTo (Copies an existing file to a new file).
  • Create (Creates a file).
  • CreateText (Creates a StreamWriter that writes a new text file).
  • Decrypt (Decrypts a file that was encrypted by the current account using the Encrypt method).
  • Delete (Permanently deletes a file).
  • Encrypt (Encrypts a file so that only the account used to encrypt the file can decrypt it).
  • MoveTo (Moves a specified file to a new location, providing the option to specify a new file name).
  • Open (Opens a file with various read/write and sharing privileges).
  • OpenRead (Create a read-only FileStream).
  • OpenText (Creates a StreamReader with UTF8 encoding that reads from an existing text file).
  • OpenWrite (Creates a write-only FileStream).
  • Refresh (Refreshes the state of the object).
  • Replace (Replaces the contents of a specified file with the file described by the current FileInfo object, deleting the original file, and creating a backup of the replaced file).

FileSystemInfo Class

The System.IO namespace contains types that allow reading & writing to files and data streams, and types that provide basic file and directory support.

FileSystemInfo Class
Provides the base class for both FileInfo & DirectoryInfo objects.
The FileSystemInfo class contains methods that are common to file and directory manipulation. A FileSystemInfo object can represent either a file or a directory, thus serving as the basis for FileInfo or DirectoryInfo objects.


When first called, FileSystemInfo calls Refresh and returns the cached information on APIs to get attributes and so on. On subsequent calls, you must call Refresh to get the latest copy of the information.

A derieved class can inherit from FileSystemInfo only if the derieved class has the AllAccess permission from the FileInfoPermissionAccess enumeration.

Common I/O Tasks are covered in detail here http://msdn2.microsoft.com/en-us/library/ms404278.aspx

Common Members

  • Attributes (Gets/Sets the FileAttributes of the current FileSystemInfo).
  • CreationTime (Gets/Sets the creation time of the current FileSystemInfo object).
  • Exists (Gets a value indicating whether a file or directory exists).
  • Extension (Gets the string representing the extension part of the file).
  • FullName (Gets the full path of the directory or file).
  • LastAccessTime (Gets/Sets the time the current file or directory was last accessed).
  • LastWriteTime (Gets/Sets the time when the current file or directory was last written to).
  • Name (For files, gets the name of the file. For directories, gets the name of the last directory in the hierarchy if a hierarchy exists. Otherwise, the Name property gets the name of the directory).
FileIOPermission Class
Controls the ability to access files & folders. This permission distinguishes between the following four types of file IO access provided by FileIOPermissionAccess enumeration.
  • Read (Read access to the contents of the file or access to information about the file, such as its length or last modification time).
  • Write (Write access to the contents of the file or access to change information about the file, such as its name. Also allows for deletion and overwriting).
  • Append (Ability to write to the end of a file only. No ability to read).
  • PathDiscovery (Access to the information in the path itself. This helps protect sensitive information in the path, such as user names, as well as information about the directory structure revealed in the the path. This value does not grant access to files or folders represented by the path).

What Next?

For those of you who haven't noticed my revision follows the book 'MCTS Self-Paced Training Kit (Exam 70-536): Microsoft .NET Framework 2.0 - Application Development Foundation'. Why do I bother writing a blog on it? Because my memory is awful and instead of me taking notes on a piece of paper next to me whilst I revise I use this blog. Also useful when I remember looking at x in work and need to look-up the exact details of x I don't have to re-lookup it up, I can use my blog.

So what am I looking at next, well if you have the book that I am using you will know I am going to say:

Access files & folders by using the File System classes.

  • File class and FileInfo class.
  • Directory class and DirectoryInfo class.
  • DriveInfo class and DriveType enumeration.
  • FileSystemInfo class and FileSystemWatcher class.
  • Path class.
  • ErrorEventArgs and ErrorEventHandler delegate.
  • RenamedEventArgs class and RenamedEventHandler delegate.

Manage byte streams by using Stream classes

  • FileStream class.
  • Stream class (not Reader & Writer classes as they are covered separately)
  • MemoryStream class
  • BufferedStream class

Manage the .NET Framework application data by using Reader & Writer classes

  • StringReader class and StringWriter class.
  • TextReader class and TextWriter class.
  • StreamReader class and StreamWriter class.
  • BinaryReader class and BinaryWriter class.

Compress or decompress stream information in a .NET Framework application

  • IsolatedStorageFile class.
  • IsolatedStorageFileStream class.
  • DeflateStream class.
  • GZipStream class.

Friday, 2 February 2007

Test Yourself

Things you should be able to do by now if you have been following along and doing abit of your own research on the subject areas that have been mentioned.

  • Create two classes with identical functionality. Use generics for one and cast the second class to Object types. Create a foor loop that uses the class over thousands of iterations, test the timing's of both classes, which is faster, by how much?
  • Create a custom class that implements the necessary interfaces to allow sorting of an array containg your custom class.
  • Create a custom class that can be converted to common value types.
  • Create a custom class, which uses the operator keyword to take care of narrowing & widening conversions.
  • Create a custom class, which implements IDisposable.Dispose method.
  • Write a custom event handler and respond to your events within a class.

Thursday, 1 February 2007

The Generic EventHandler delegate

.NET 2.0 introduces a generic event handler delegate, the following example shows you how to use the new syntax.

public event EventHandler<EventArgs> RaiseCustomEvent;

protected virtual void
OnRaiseCustomEvent(EventArgs e)
{
EventHandler
<EventArgs> handler =
RaiseCustomEvent;

if (handler != null
)
{
handler(
this
, e);
}
}

void HandleCustomEvent(object
sender, EventArgs e)
{
Console.WriteLine(
"Event Received"
);
}

public static void
Main()
{
MyClass ourClass
= new
MyClass();

// Subscribe to event

ourClass.RaiseCustomEvent += ourClass.HandleCustomEvent;

// How to raise an event.

ourClass.OnRaiseCustomEvent(new EventArgs());
}