C# 練習題 (10)

C# 練習題 (10)

練習題 (10): Create files with date and time stamp appended to the name

本題利用 FileInfo 類別,來實作該改檔案名稱的動作。

程式碼:

  1. using System;
  2. using System.IO;
  3. namespace AppendDateAndTime
  4. {
  5. internal class Program
  6. {
  7. private static void Main( string [ ] args)
  8. {
  9. DateTime dt = DateTime.Now;
  10. string s = String.Format ( "{0:yyyyMMdd_HHmmss}", dt);
  11. string oldFileName = "test.txt";
  12. StreamWriter sw = new StreamWriter(oldFileName);
  13. sw.WriteLine ( "This is a test file." );
  14. sw.Flush ( );
  15. sw.Close ( );
  16. sw.Dispose ( );
  17. FileInfo fi = new FileInfo(oldFileName);
  18. string newFileName = fi.Name.Replace (fi.Extension, "" ) + "_" + s + fi.Extension;
  19. fi.MoveTo (newFileName);
  20. }
  21. }
  22. }