練習題 (10): Create files with date and time stamp appended to the name
本題利用 FileInfo 類別,來實作該改檔案名稱的動作。
程式碼:
-
using System;
-
using System.IO;
-
namespace AppendDateAndTime
-
{
-
internal class Program
-
{
-
private static void Main( string [ ] args)
-
{
-
DateTime dt = DateTime.Now;
-
string s = String.Format ( "{0:yyyyMMdd_HHmmss}", dt);
-
string oldFileName = "test.txt";
-
StreamWriter sw = new StreamWriter (oldFileName );
-
sw.WriteLine ( "This is a test file." );
-
sw.Flush ( );
-
sw.Close ( );
-
sw.Dispose ( );
-
FileInfo fi = new FileInfo (oldFileName );
-
string newFileName = fi.Name.Replace (fi.Extension, "" ) + "_" + s + fi.Extension;
-
fi.MoveTo (newFileName);
-
}
-
}
-
}
|