Permalink
Cannot retrieve contributors at this time
Fetching contributors…
| // <Snippet21> | |
| using System; | |
| using System.Globalization; | |
| using System.IO; | |
| using System.Text; | |
| using System.Threading; | |
| public class Example | |
| { | |
| private static string filename = @".\dates.dat"; | |
| public static void Main() | |
| { | |
| DateTime[] dates = { new DateTime(1758, 5, 6, 21, 26, 0), | |
| new DateTime(1818, 5, 5, 7, 19, 0), | |
| new DateTime(1870, 4, 22, 23, 54, 0), | |
| new DateTime(1890, 9, 8, 6, 47, 0), | |
| new DateTime(1905, 2, 18, 15, 12, 0) }; | |
| // Write the data to a file using the current culture. | |
| WriteData(dates); | |
| // Change the current culture. | |
| Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-CH"); | |
| // Read the data using the current culture. | |
| DateTime[] newDates = ReadData(); | |
| foreach (var newDate in newDates) | |
| Console.WriteLine(newDate.ToString("g")); | |
| } | |
| private static void WriteData(DateTime[] dates) | |
| { | |
| StreamWriter sw = new StreamWriter(filename, false, Encoding.UTF8); | |
| for (int ctr = 0; ctr < dates.Length; ctr++) { | |
| sw.Write("{0}", dates[ctr].ToString("g", CultureInfo.CurrentCulture)); | |
| if (ctr < dates.Length - 1) sw.Write("|"); | |
| } | |
| sw.Close(); | |
| } | |
| private static DateTime[] ReadData() | |
| { | |
| bool exceptionOccurred = false; | |
| // Read file contents as a single string, then split it. | |
| StreamReader sr = new StreamReader(filename, Encoding.UTF8); | |
| string output = sr.ReadToEnd(); | |
| sr.Close(); | |
| string[] values = output.Split( new char[] { '|' } ); | |
| DateTime[] newDates = new DateTime[values.Length]; | |
| for (int ctr = 0; ctr < values.Length; ctr++) { | |
| try { | |
| newDates[ctr] = DateTime.Parse(values[ctr], CultureInfo.CurrentCulture); | |
| } | |
| catch (FormatException) { | |
| Console.WriteLine("Failed to parse {0}", values[ctr]); | |
| exceptionOccurred = true; | |
| } | |
| } | |
| if (exceptionOccurred) Console.WriteLine(); | |
| return newDates; | |
| } | |
| } | |
| // The example displays the following output: | |
| // Failed to parse 4/22/1870 11:54 PM | |
| // Failed to parse 2/18/1905 3:12 PM | |
| // | |
| // 05.06.1758 21:26 | |
| // 05.05.1818 07:19 | |
| // 01.01.0001 00:00 | |
| // 09.08.1890 06:47 | |
| // 01.01.0001 00:00 | |
| // 01.01.0001 00:00 | |
| // </Snippet21> |