Posted By

denakitan on 10/17/12


Tagged

io Net directory DateTime basics parsing examples c#


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

thastyle
Priestd09
danfinrud55


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


 / Published in: C#
 

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

  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  

You need to login to post a comment.