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
Create a new Microsoft Visual C# development tool class library project called FileIO and rename class1.cs to FileIO.cs .
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.
Use a fixed assembly version. Open Assemblyinfo.cs and set the AssemblyVersion attribute as shown below:
[assembly: AssemblyVersion("1.0.0.1")]
Add the following using statements to the top of FileIO.cs:
using System.IO; using System.Text;
Rename Class1 to FileWrapper and seal the class to prevent inheritance.
public sealed class FileWrapper
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.
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(); } }