Sometimes as a developer you need to rename a file with a date time aspect so you can do something like guarantee uniqueness, track submission information, etc. There's always a ton of ways to do this, but I decided to write a couple of routines to do this using the FileInfo class. First, the code:
/// <summary>
/// Gets a string you can append in a file name to supply uniqueness
/// </summary>
/// <returns>a string which looks similar to 2232005_090812 which is a date time</returns>
public static string GetUniqueFileNameIdentifier()
{
return DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Year.ToString()+ "_" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
}
/// Renames a file with a unique identifier in it
/// <param name="fileName">file name to rename..</param>
/// <returns>unique name of file with datetime identifier in the name. e.g. MyFile.txt renamed to MyFile_2232005_090812.txt </returns>
public static string FormatUniqueFileName(string fileName)
FileInfo fi = new FileInfo(fileName);
return fi.Name.Replace(fi.Extension,"") + "_" + GetUniqueFileNameIdentifier() + fi.Extension;
First, the FormatUniqueFileName funtion takes a file name (like test.txt), and inserts the date time info (in the current format, it does this as fileprefix_mmddyyyy_hhmmss.fileextension, so in our example, we might get test_03162005_071525.txt.
Not a real complex function by any means, but one that's reused a lot in development, and I decided to get this out just in case some developer wanted to save 5 minutes!
Enjoy!
Powered by: newtelligence dasBlog 2.3.9074.18820
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2012, © Copyright 2010
E-mail