/ Published in: C#
Example of the usage of Directory IO class and the parsing of strings to DateTime.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
string directoryPath = string.Empty; try { // suppose that the sub-directories of directoryPath contain Ghibli movies information, each directory is named after the release date of the particular movie, in the format yyyyMMdd directoryPath = ConfigurationManager.AppSettings["DirectoryPath"]; string[] subDirectories = Directory.GetDirectories(directoryPath); foreach (string directory in subDirectories) { string currentDirectory = directory.Substring(directory.LastIndexOf('\\') + 1); try { // parsing the directory name to create a DateTime object DateTime releaseDate = DateTime.ParseExact(currentDirectory, "yyyyMMdd", new CultureInfo("en-US", false)); // getting the month name from the month number string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(releaseDate.Month); Console.WriteLine(string.Format("Found a movie that was released on {0}, {1}.", monthName, releaseDate.Year)); } catch (FormatException) { // could not parse due to the format of directory name continue; } catch(Exception ex) { Console.WriteLine(ex.Message); } } } catch (UnauthorizedAccessException uaex) { Console.WriteLine(string.Format("Access to {0} was denied. Error message: {1}", directoryPath, uaex.Message)); } catch (Exception ex) { Console.WriteLine(ex.Message); }