The following example deserializes a TimeZoneInfo object stored in an embedded .NET XML resource file.
Private Sub DeserializeTimeZones()
Dim cst, palmer As TimeZoneInfo
Dim timeZoneString As String
Dim resMgr As ResourceManager = New ResourceManager("SerializeTimeZoneData.SerializedTimeZones", Assembly.GetExecutingAssembly)
' Attempt to retrieve time zone from system
Try
cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")
Catch ex As TimeZoneNotFoundException
' Time zone not in system; retrieve from resource
timeZoneString = resMgr.GetString("CentralStandardTime")
If Not String.IsNullOrEmpty(timeZoneString) Then
cst = TimeZoneInfo.FromSerializedString(timeZoneString)
Else
MsgBox("Unable to create Central Standard Time Zone. Application must exit.")
Exit Sub
End If
End Try
' Retrieve custom time zone
Try
timeZoneString = resMgr.GetString("PalmerStandardTime")
palmer = TimeZoneInfo.FromSerializedString(timeZoneString)
Catch ex As Exception
MsgBox(ex.GetType().Name & ": Unable to create Palmer Standard Time Zone. Application must exit.")
Exit Sub
End Try
End Sub
private void DeserializeTimeZones()
{
TimeZoneInfo cst, palmer;
string timeZoneString;
ResourceManager resMgr = new ResourceManager("SerializeTimeZoneData.SerializedTimeZones", Assembly.GetExecutingAssembly());
// Attempt to retrieve time zone from system
try
{
cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
}
catch (TimeZoneNotFoundException)
{
// Time zone not in system; retrieve from resource
timeZoneString = resMgr.GetString("CentralStandardTime");
if (! String.IsNullOrEmpty(timeZoneString))
{
cst = TimeZoneInfo.FromSerializedString(timeZoneString);
}
else
{
MessageBox.Show("Unable to create Central Standard Time Zone. Application must exit.", "Application Error");
return;
}
}
// Retrieve custom time zone
try
{
timeZoneString = resMgr.GetString("PalmerStandardTime");
palmer = TimeZoneInfo.FromSerializedString(timeZoneString);
}
catch (MissingManifestResourceException)
{
MessageBox.Show("Unable to retrieve the Palmer Standard Time Zone from the resource file. Application must exit.");
return;
}
}
This code illustrates exception handling to ensure that a TimeZoneInfo object required by the application is present. It first tries to instantiate a TimeZoneInfo object by retrieving it from the registry using the FindSystemTimeZoneById method. If the time zone cannot be instantiated, the code retrieves it from the embedded resource file.
Because data for custom time zones (time zones instantiated by using the CreateCustomTimeZone method) are not stored in the registry, the code does not call the FindSystemTimeZoneById to instantiate the time zone for Palmer, Antarctica. Instead, it immediately looks to the embedded resource file to retrieve a string that contains the time zone's data before it calls the FromSerializedString method.