I'm working on updating a project which uses the following code to place a file in a folder based on the date:
int month = DateTime.Now.Month;
string zero = (month < 10) ? "-0" : "-";
string folder = "Folder" + DateTime.Now.Year.ToString() + zero + month.ToString() + "\\";
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
ArchiveFolder = folder;
//...
DateTime now = DateTime.Now;
int date = now.Day;
string zero = (date < 10) ? "0" : "";
string saveaspath = zero + date.ToString() + "_" + now.ToLongTimeString() + "_" + name;
#if DOTNET20
foreach (char c in Path.GetInvalidFileNameChars())
#else
foreach (char c in Path.InvalidPathChars)
#endif
saveaspath = saveaspath.Replace(c, '-'); // substitute - for bad chars
saveaspath = saveaspath.Replace(':', '-');
string originalname = saveaspath;
string ext = ".ext";
saveaspath = Path.Combine(ArchiveFolder, saveaspath + ext);
int count = 1;
while (File.Exists(saveaspath)) // make unique
{
string num = " (" + count++.ToString() + ")";
saveaspath = Path.Combine(ArchiveFolder, originalname + num + ext);
}
Example generated file:
Folder/2010-06/18_2-42-09 PM_name.ext
This is run for each file to be created, usually many files at a time due to the nature of the program.
I was thinking about updating the concatenated DateTimes with DateTime format strings--I figured that might be more efficient than all these different ToString() etc. calls; however I'm nervous that might screw up when a user has different culture settings. Then again, this current code might do something funky--I don't know.
So: Should I redo the code using format strings? Or leave it as it is? Would it benefit performance? Would it be culture-dependent?
(To clarify: my question is not HOW to rewrite it using a format string; rather, I am concerned with the ramifications of doing so.)