.NET 2.0: Notes on Foundation Part 3 (C#)

Isolated Storage

You use isolated storage in your .NET application if you want to save information on a hard drive without using a database or other means and still have safe access to it – meaning no need to worry if application has enough rights to do so.

To create a store, use IsolatedStorageFile class, which is responsible for creating files and folders in isolated storage.  You first need to scope the data you want in the store, that is, if you like your data to be specific to the calling assembly and the local machine, or specific to the calling assembly and the current user.

// specific to assembly and local machine
IsolatedStorageFile machineStore =
IsolatedStorageFile.GetMachineStoreForAssembly();

// specific to assembly and current user
IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForAssembly();

To work with files in the store, use IsolatedStorageFileStream class, which derives from FileStream class.

IsolatedStorageFileStream userStream =
  new IsolatedStorageFileStream("UserSettings.set", FileMode.Create, userStore);

StreamWriter userWriter = new StreamWriter(userStream);
userWriter.WriteLine("User Prefs");
userWriter.Close();

IsolatedStorageFileStream userStream =
  new IsolatedStorageFileStream("UserSettings.set", FileMode.Open, userStore);
string[] files = userStore.GetFileNames("UserSettings.set");
if (files.Length == 0)
{
  Console.WriteLine("No data saved for this user");
}
else
{
  // …
}

You can also work with directories using the methods found in the IsolatedStorageFile class, such as CreateDirectory() and GetDirectoryNames().

Last important point in using isolated storage is that you have to explicitly permission your code to access it by annotating your class or method with the IsolatedStorageFilePermission class.

[IsolatedStorageFilePermission(SecurityAction.Demand,
  UserQuota=1024,
  UsageAllowed=IsolatedStorageContainment.AssemblyIsolationByUser)]
class MyClass
{
// …
}

 

Regular Expressions

To use regular expressions in your application, you use System.Text.RegularExpressions.Regex class.

// checks if input string matches regular expression
if (Regex.IsMatch(regexString, inputString)
  Console.WriteLine("Input matches regular expression.");
else
  Console.WriteLine("Input DOES NOT match regular expression.");

// extracts matched data
string inputString = "Company Name: MyCompany, Inc.";
Match m = Regex.Match(inputString, @"Company Name: (.*$)");
Console.WriteLine(m.Groups[1]);

// reformats extracted substring
Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/",
RegexOptions.Compiled);
Console.WriteLine(r.Match(urlString).Result("${proto}${port}"));

// replaces substring
// in this example, it replaces mm/dd/yy with dd-mm-yy
Console.WriteLine(Regex.Replace(inputString,
  "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",
  "${day}-${month}-${year}"));

For quick help on how to form regular expressions go to this link, which is a cheat sheet by the way.

 

Encoding and Decoding

To work with encodings, use the System.Text.Encoding class.

// converts from one code page to another
// get Korean encoding
Encoding e = Encoding.GetEncoding("Korean");
// convert ASCII bytes to Korean encoding
byte[] encoded;
encoded = e.GetBytes("Hello, world!");
// display the byte codes
for (int i = 0; i < encoded.Length; i++)
  Console.WriteLine("Byte {0}: {1}", i, encoded[i]);

// examines supported code pages
EncodingInfo[] eis = Encoding.GetEncodings();
foreach (EncodingInfo ei in eis)
{
  Console.WriteLine("{0}: {1}, {2}", ei.CodePage, ei.Name, ei.DisplayName);
}

// specifies encoding type when writing a file
StreamWriter utf7Writer = new StreamWriter("utf7.txt", false, Encoding.UTF7);
utf7Writer.WriteLine("Hello World!!!");
utf7Writer.Close();

// specifies encoding type when reading a file
StreamReader utf7Reader = new StreamReader("utf7.txt", Encoding.UTF7);
Console.WriteLine(utf7Reader.ReadToEnd());
utf7Reader.Close();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s