Step 1. Create an Assembly That Performs File IO


Step 1. Create an Assembly That Performs File I/O

In this step, you create an assembly that performs file I/O using a supplied filename.

 Task   To create a new assembly that performs file I/O

  1. Create a new Microsoft Visual C# development tool class library project called FileIO and rename class1.cs to FileIO.cs .

  2. Add a strong name to the assembly.

    By adding a strong name, you make the assembly tamper proof by digitally signing it. The public key component of the strong name also provides cryptographically strong evidence for code access security policy. An administrator can apply policy by using the strong name to uniquely identify the assembly.

  3. Use a fixed assembly version. Open Assemblyinfo.cs and set the AssemblyVersion attribute as shown below:

     [assembly: AssemblyVersion("1.0.0.1")] 
  4. Add the following using statements to the top of FileIO.cs:

     using System.IO; using System.Text; 
  5. Rename Class1 to FileWrapper and seal the class to prevent inheritance.

     public sealed class FileWrapper 
  6. Rename the default constructor to match the class name and change it to private , which prevents instances of the FileWrapper class from being created. This class provides static methods only.

  7. Add the following public method so that it reads from a specified file.

     public static string ReadFile(string filename) {   byte[] fileBytes = null;   long fileSize = -1;   Stream fileStream = null;       try   {     if(null == filename)     {       throw new ArgumentException("Missing filename");     }     // Canonicalize and validate the supplied filename     // GetFullPath:     // - Checks for invalid characters (defined by Path.InvalidPathChars)     // - Checks for Win32 non file-type device names including     //   physical drives, parallel and serial ports, pipes, mail slots,     //   and so on     // - Normalizes the file path         filename = Path.GetFullPath(filename);     fileStream = File.OpenRead(filename);     if(!fileStream.CanRead)     {       throw new Exception("Unable to read from file.");     }     fileSize = fileStream.Length;     fileBytes = new byte[fileSize];     fileStream.Read(fileBytes, 0, Convert.ToInt32(fileSize));     return Encoding.ASCII.GetString(fileBytes);   }   catch (Exception ex)   {     throw ex;   }   finally   {     if (null != fileStream)       fileStream.Close();   } } 



Improving Web Application Security. Threats and Countermeasures
Improving Web Application Security: Threats and Countermeasures
ISBN: 0735618429
EAN: 2147483647
Year: 2003
Pages: 613

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net