删除然后重新创建超过x天的文件c#keep createdDate

时间:2014-09-02 15:48:57

标签: c# ssis

我正在我的SSIS包中编写一个脚本任务,如果它超过X天数,则删除包使用的日志文件。这是我目前的代码:

if (File.Exists((String)Dts.Variables["ErrorLogLocation"].Value))
        {

            DateTime logCreatedDate = File.GetCreationTime((String)Dts.Variables["ErrorLogLocation"].Value);

            if (logCreatedDate < DateTime.Now.AddDays(-3))
            {
                try
                {
                    File.Delete((String)Dts.Variables["ErrorLogLocation"].Value);
                }
                catch (Exception e)
                {
                    using (StreamWriter sw = File.AppendText((String)Dts.Variables["ErrorLogLocation"].Value))
                    {
                        sw.WriteLine(DateTime.Now + " : "+ e);
                    }
                }

                using (StreamWriter sw = File.AppendText((String)Dts.Variables["ErrorLogLocation"].Value))
                {
                    sw.WriteLine("New log Creation Date: " + File.GetCreationTime((String)Dts.Variables["ErrorLogLocation"].Value));
                }

            }
        }

它似乎可以工作,但问题是当我删除文件,然后写入具有相同名称的新文件时,内部信息正在按预期擦除,但文件创建日期保持不变删除。这是一个问题,因为我基于何时在该日期时删除此文件。我想到的预期行为是删除文件,然后使用新创建的日期写入一个全新的文件。

知道可能导致这种情况的原因吗?是因为我正在删除一个文件,然后立即附加到一个具有相同名称的文件(如果它不存在,我会假设它只会创建一个新文件?)这个文件是否仍然保留在内存中或者其他内容中周期?

1 个答案:

答案 0 :(得分:1)

来自documentation

  

NTFS格式的驱动器可能会缓存有关文件的信息,例如文件   创作时间,在短时间内。结果,它可能是   必要时显式设置文件的创建时间   覆盖或替换现有文件。

根据此信息,您必须致电File.SetCreationTime以确保其获得所需的时间戳。