Extension methods allow you to extend "existing" classes that you otherwise would not have access to; in the example the follows I'll extend string with two new methods.
We'll start at the beginning - with the Unit Test. The MockData.StrToFile(filename) will take the contents of MockData and write it to the specified filename:
The app_dataPath string is a filename, on it we'll use the app_dataPath.FileToStr() method to return the contents of app_dataPath to the results string. The great part about extensions is the ease in which you can create them - the only difference between them and static methods is the "this" statement in front of the first parameter; it will always be the type that is being extending - in our case below "string".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Library.Utility.Extensions
{
public static class StringExtensions
{
/// <summary>
/// Send string to specified filename
/// </summary>
/// <param name="data"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static bool StrToFile(this string data, string fileName)
{
//Check if the sepcified file exists
if (System.IO.File.Exists(fileName) == true)
{
// If so then Erase the file first as in this case
// we are overwriting
System.IO.File.Delete(fileName);
}
//Create the file if it does not exist and open it
FileStream oFs = new
FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite);
//Create a writer for the file
StreamWriter oWriter = new StreamWriter(oFs);
//Write the contents
oWriter.Write(data);
oWriter.Flush();
oWriter.Close();
oFs.Close();
return true;
}
/// <summary>
/// Return file contents as string
/// </summary>
/// <param name="cFileName"></param>
/// <returns></returns>
public static string FileToStr(this string cFileName)
{
//Create a StreamReader and open the file
StreamReader oReader = System.IO.File.OpenText(cFileName);
//Read all the contents of the file in a string
string lcString = oReader.ReadToEnd();
//Close the StreamReader and return the string
oReader.Close();
return lcString;
}
}
}
Tags:
extension
Categories: