.NET - C# - Basics - Examples - Directory IO and DateTime Parsing


/ Published in: C#
Save to your folder(s)

Example of the usage of Directory IO class and the parsing of strings to DateTime.


Copy this code and paste it in your HTML
  1. string directoryPath = string.Empty;
  2.  
  3. try
  4. {
  5. // 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
  6. directoryPath = ConfigurationManager.AppSettings["DirectoryPath"];
  7. string[] subDirectories = Directory.GetDirectories(directoryPath);
  8.  
  9. foreach (string directory in subDirectories)
  10. {
  11. string currentDirectory = directory.Substring(directory.LastIndexOf('\\') + 1);
  12.  
  13. try
  14. {
  15. // parsing the directory name to create a DateTime object
  16. DateTime releaseDate = DateTime.ParseExact(currentDirectory, "yyyyMMdd", new CultureInfo("en-US", false));
  17.  
  18. // getting the month name from the month number
  19. string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(releaseDate.Month);
  20. Console.WriteLine(string.Format("Found a movie that was released on {0}, {1}.", monthName, releaseDate.Year));
  21.  
  22. }
  23. catch (FormatException)
  24. {
  25. // could not parse due to the format of directory name
  26. continue;
  27. }
  28. catch(Exception ex)
  29. {
  30. Console.WriteLine(ex.Message);
  31. }
  32. }
  33. }
  34. catch (UnauthorizedAccessException uaex)
  35. {
  36. Console.WriteLine(string.Format("Access to {0} was denied. Error message: {1}", directoryPath, uaex.Message));
  37. }
  38. catch (Exception ex)
  39. {
  40. Console.WriteLine(ex.Message);
  41. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.