Will this DateTime optimization cause localization problems? Will it be more efficient? Is it worth it?
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.)
Should I redo the code using format strings?
It would be a lot more robust and maintainable if it were simplified to use format strings.
Or leave it as it is?
If not breaking the existing behaviour is very important to you then it might be best to leave it. On the other hand, if it turns out that there is a bug in the existing code then it might be a good oppurtunity to rewrite it from scratch.
Would it benefit performance?
If your code is writing to files I hardly think the time spent creating the strings will be the bottleneck. Writing to a file is a very slow operation in comparison.
Would it be culture-dependent?
Use CultureInfo.InvariantCulture
when formatting to avoid culture dependence.
Yes. You should face fewer, rather than more, localization issues when using a format string rather than the use-current-culture versions of the ToString method calls you are using now.
精彩评论