Locked History Actions

MicrosoftCertification/70-536/MyNotes/InputOutput

.NET Framework Assemblies, Namespaces, Classes, Enumerations, Delegates, etc.

Directory and File Related

  • System.IO namespace
  • File (static/utility) and FileInfo (derives from FileSystemInfo which is abstract)

  • Directory (static/utility) and DirectoryInfo (derives from FileSystemInfo which is abstract)

  • DriveInfo and DriveType enumeration

  • FileSystemInfo and FileSystemWatcher

  • Path (static/utility)
  • ErrorEventArgs and ErrorEventHandler delegate

  • RenamedEventArgs and RenamedEventHandler delegate

FileInfo, DirectoryInfo, DriveInfo and Path

Below is some sample code (Iron Python) do demonstrate the use of these utility (static) classes

from System.IO import *
from System.Threading import *

# using FileInfo to test for the existance of a file
# and obtain properties of it
fi = FileInfo(r"c:\boot.ini")
if fi.Exists:
 print "Name is: %s" % fi.Name
 print "FullName is: %s" % fi.FullName
 print 
 
# using FileInfo to make a copy of a file
try:
    fi.CopyTo(r"c:\boot.bak")
except:
    pass # must already exist
    
# using DirectoryInfo to enumerate files in a directory
di = DirectoryInfo(r"c:\windows")
files = di.GetFiles() # returns an collection of FileInfo objects
for file in files:
    print file.Name
    
# use DriveInfo to enumerate the drives on a system
drives = DriveInfo.GetDrives()
for drive in drives:
    print "drive %s is of type %s" % (drive.Name, drive.DriveType)
    
    
# use the Path class to change file's extention
# Note that the ChangeExtension() method only generates the name, it
# doesn't actually change the file
path = r"c:\boot.ini"
print "Original file name is %s" % path
print "The new extention (could) be %s" % Path.ChangeExtension(path, "bak")
print 


# Watch for changes in files and/or directories
fw = FileSystemWatcher()
fw.Path = r"C:\\"

def FileSystemEventHandler(*args):
    print args

def FileSystemEventErrorHandler(*args):
    print args

# errors can occur during watching, hookup error handler
fw.Error += FileSystemEventErrorHandler
fw.Created += FileSystemEventHandler
fw.EnableRaisingEvents = True

print "Sleeping ..."
Thread.Sleep(12000)
print "Done"

Stream Related

  • Namespace: System.IO
  • Class: Stream (abstract)
    • Stream derivatives: FileStream, MemoryStream, CryptoStream, NetworkStream , GZipStream

  • Class: File - utility (static) class for working with files.
  • Class: FileStream

    • FileStream "wrappers" StreamReader, StreamWriter - read/write files as strings rather than bytes. They derive from TextReader and TestWriter respectively

    • FileStream "wrappers" BinaryReader, BinaryWriter

  • FileAccess and FileMode

    • FileAccess controls "Read", "Write" or "ReadWrite" access to the file

    • FileMode controls "Append", "Create", "CreateNew", "Open", "OpenOrCreate", "Truncate"

  • Class: MemoryStream

  • Class: BufferedStream

Sample Code

Here is some code demonstrating the use of these classes

The expected output is

Streams and Compression

* Class: !GZipStream, DeflateStream

  • These use the same compression algorithm but GZip add some meta data via headers, DeflateStream has slightly less overhead

  • GZip includes a CRC to check for errors, its safer, but slower
  • Use these a wrappers around other stream objects

Iron Python Sample Code

# compression and uncompressing files

from System.IO import *
from System.IO.Compression import *

srcStream = File.Open(r"c:\test.txt", FileMode.Open)
dstStream = File.Open(r"c:\test.txt.gz", FileMode.Create)
gzip = GZipStream(dstStream, CompressionMode.Compress)
byte = srcStream.ReadByte()
while byte != -1:
    gzip.WriteByte(byte)
    byte = srcStream.ReadByte()
srcStream.Close()
dstStream.Close()
print "File size before = %s, file size after %s" % (FileInfo(r"c:\test.txt").Length, FileInfo(r"c:\test.txt.gz").Length)
print 

# uncompress
srcStream = File.Open(r"c:\test.txt.gz", FileMode.Open)
dstStream = File.Open(r"c:\test.txt.txt", FileMode.Create)
gzip = GZipStream(srcStream, CompressionMode.Decompress)
byte = gzip.ReadByte()
while byte != -1:
    dstStream.WriteByte(byte)
    byte = gzip.ReadByte()
srcStream.Close()
gzip.Close()
dstStream.Close()
print "File size before = %s, file size after %s" % (FileInfo(r"c:\test.txt.gz").Length, FileInfo(r"c:\test.txt.txt").Length)
print

The output

File size before = 41, file size after 144

Hmmm, interesting.

Isolated Storage

  • class IsolatedStorageFile (utility class)

  • class IsolatedStorageFileStream (derives from FileStream)

The IsolatedStorageFile class contains a number of static methods that act as factory methods to create instances of IsolatedStorageFile that pertain to isolated storage for a particular scope or context. These are listed here in the API documentation:

GetMachineStoreForApplication

Obtains machine-scoped isolated storage corresponding to the calling code's application identity. (used for ClickOnce applications)

GetMachineStoreForAssembly

Obtains machine-scoped isolated storage corresponding to the calling code's assembly identity.

GetMachineStoreForDomain

Obtains machine-scoped isolated storage corresponding to the application domain identity and the assembly identity.

GetUserStoreForApplication

Obtains user-scoped isolated storage corresponding to the calling code's application identity.

GetUserStoreForAssembly

Obtains user-scoped isolated storage corresponding to the calling code's assembly identity.

GetUserStoreForDomain

Obtains user-scoped isolated storage corresponding to the application domain identity and assembly identity.

Sample Code

Again I wanted to use IronPython but I observed exceptions when attempting to make calls on IsolatedStorageFile so we'll use C# here:

using System;
using System.IO;
using System.IO.IsolatedStorage;

namespace _70_536_new
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get isolated storage for the assembly
            // and write some data
            IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForAssembly();

            // create a directory first
            isoFile.CreateDirectory("mydir");

            IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(
                @"mydir\UserSettings.set", System.IO.FileMode.Create, isoFile);
            StreamWriter sw = new StreamWriter(isoStream);
            sw.WriteLine("my data");
            sw.Close();

            IsolatedStorageFileStream isoStreamForRead = new IsolatedStorageFileStream(
                @"mydir\UserSettings.set", FileMode.Open, isoFile);
            StreamReader sr = new StreamReader(isoStreamForRead);
            Console.WriteLine(sr.ReadLine());
            sr.Close();

            
        }
    }
}

Notice one can create directories in which to store data using the CreateDirectory() method. I found that if the directory exists the method returns without exception. One other interesting thing to note that there is no equal to File.Exists() for Isolated Storage. The equivelent is the method GetFileNames() method on the IsolatedStorageFile class. Same for directorys. Use the GetDirectoryNames() method.

One last thing. Permission access can be declared using the IsolatedStorageFilePermissionAttribute class like this:

    [IsolatedStorageFilePermission(SecurityAction.Demand,
        UserQuota=1024,
      UsageAllowed=IsolatedStorageContainment.AssemblyIsolationByUser)]
    class Program
    {

Book Feedback

  • The questions at the end of chapter one includes a question about the class File even though that class is not introduced/discussed until chapter 2. (Bozo editing!).


CategoryMicrosoftCertification