问题
I have a requirement where my scheduler will run twice in a day. One in the morning and a second time in evening. When I run my current code it stores the file in a folder.
So again when I run the same application in the evening what happens is that the same file which is saved earlier in the morning is getting updated again which I don't want to happen. I want to save both the files. So what should I do?
Below is my current code. Please give me suggestions
public void ExportExcel(string strWorkbookName, DataSet ds)
{
string strDateFolder = "";
string strFileName = ConfigurationManager.AppSettings["FileName"].ToString();
try
{
using (XLWorkbook wb = new XLWorkbook())
{
strDateFolder = DateTime.Now.ToString("dd-MM-yyyy");
if (Directory.Exists(strDateFolder))
{
Directory.CreateDirectory(strDateFolder);
}
wb.Worksheets.Add(ds);
wb.SaveAs(ConfigurationRead.GetAppSetting("ReportDirectory") + "\\" + strDateFolder + "\\" + strFileName);
}
}
catch (Exception)
{
throw;
}
}
UPDATE
Also, I want to delete the folder created after 7 days..Is that also possible ?
回答1:
strDateFolder will contain the same value through both runs because it gets the date. You may want to add time to that so it creates another file. Like this:
strDateFolder = DateTime.Now.ToString("dd-MM-yyyy-hh");
Then, the code below is like saying: if this directory exists, create it.
if (Directory.Exists(strDateFolder))
{
Directory.CreateDirectory(strDateFolder);
}
You can use only this, because it will create it only if it does not exist:
Directory.CreateDirectory(strDateFolder);
Update from post: This would delete your folders older that 6 days
CultureInfo enUS = new CultureInfo("en-US");
string path = ConfigurationRead.GetAppSetting("ReportDirectory");
DateTime currentDate = DateTime.Now.AddDays(-7);
foreach (string s in Directory.GetDirectories(path))
{
string folderPath = s.Remove(0, path.Length);
if (DateTime.TryParseExact(folderPath, "dd-MM-yyyy hhmmss", enUS, DateTimeStyles.AssumeLocal, out DateTime td))
{
if (td <= currentDate)
{
Directory.Delete(s, true);
}
}
}
来源:https://stackoverflow.com/questions/49192917/running-the-scheduler-twice-is-updating-the-file-with-the-earlier-file-in-consol