每小时创建一个csv文件?

时间:2015-12-16 10:15:39

标签: c# .net

我必须每小时创建一个csv文件。我需要为当天创建一个目录 在那天的同一目录中,我必须每小时创建一个文件

public string CreateFile()
{
    string rootDirectory = ConfigurationManager.AppSettings["BasePath"].ToString();
    string directoryName = "tracker-" + DateTime.Now.ToString("MM-dd-yyyy"); 
    string fileName = "tracker-" + DateTime.Now.ToString("MM-dd-yyyy") + ".csv"; //here i want the file to be for every hour
    string directoryPath=Path.Combine(rootDirectory, directoryName)
    string path = Path.Combine(directoryPath, filename);
    if (!Directory.Exists(directoryName))
    {
          Directory.CreateDirectory(directoryName);
    }

    if (!System.IO.File.Exists(path))
    {
        System.IO.File.Create(path).Dispose();
        using (TextWriter tw = new StreamWriter(path))
        {
            tw.WriteLine("New file created");
            tw.Close();
        }
    }
    return path;
}

任何人都可以帮助我。

2 个答案:

答案 0 :(得分:0)

如果您的意思是每小时需要一个应用程序来创建csv文件,那么您可以使用Timer

Timer _tmrCsv = new Timer { Interval = 3600000 };
private void Form2_Load(object sender, EventArgs e)
{
    _tmrCsv.Tick += _tmrCsv_Tick;
    _tmrCsv.Enabled = true;

}

void _tmrCsv_Tick(object sender, EventArgs e)
{
    CreateFile();
}

答案 1 :(得分:0)

您可以使用Timer

以下是示例代码:

 private static System.Timers.Timer aTimer;
 private static int counter = 0;
 private static void SetTimer()
{
    // Create a timer with a one minute interval.
    aTimer = new System.Timers.Timer(60000);
    // Hook up the Elapsed event for the timer. 
    aTimer.Elapsed += OnTimedEvent;
    aTimer.AutoReset = true;
    aTimer.Enabled = true;
}

  private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    //Increment the counter
     counter++;

     if (counter== 60)
     {
        // One hour has passed
        // Reset the counter and create your file
        counter = 0;
        CreateFile();
     }
}