c#删除文件遇到问题

来源:互联网 发布:c语言的基础知识 编辑:程序博客网 时间:2024/06/07 03:23

      昨天需要写一个c#中删除记得log日志文件的程序。比如,我的一个程序需要有log,我把log写到log日志文件中,每一个月我自动建一个log文件。这个log文件是以类似"xxx04.log"命名的,其中xxx是我的项目名称,04代表4月份log。

      从log日志命名上来看,下一年的四月的log也会写在里面,这样就显得比较混乱并且log日志会非常大,所以我想下一年到4月先把"xxx04.log"这个log删除,然后再创建一个同名(“xxx04.log”)。

      先贴上代码吧:

class RecordLog

    {        public FileStream fs = null;        public StreamWriter sw = null;        public string Dir = @"D:\xxx";        /// <summary>        /// 读取或者新建日志文件        /// </summary>        public RecordLog()        {            try            {                if (!Directory.Exists(Dir))// 目录不存在,新建目录                {                    Directory.CreateDirectory(Dir);                }                DeleteFile();                //add end                 fs = new FileStream(                          Dir + "\\" + getFileName(),                          FileMode.Create | FileMode.Append,                          FileAccess.Write,                          FileShare.None);                fs.Seek(0, System.IO.SeekOrigin.End);                sw = new StreamWriter(fs, System.Text.Encoding.UTF8);            }            catch (Exception ex)            {                MessageBox.Show("Exception" + ex.Message);                if (sw != null)                {                    sw.Close();                    sw = null;                }                if (fs != null)                {                    fs.Close();                    fs = null;                }            }        }        public string getFileName()//根据不同月份,新建不同的日志文件        {            DateTime dt = DateTime.Now;            int month = dt.Month;            string strMonth = (month > 10) ? month.ToString() : "0" + month.ToString();                        return "xxx"+strMonth+".log";        }        /// <summary>        /// 写日志        /// </summary>        /// <param name="info">需要写的日志信息</param>        public void WriteLog(string info)        {            DateTime dt = DateTime.Now;            string tmp = dt.ToString();            string tmp1 = tmp.Substring(0, tmp.IndexOf("-")+1) + "0" + tmp.Substring(tmp.IndexOf("-")+1);            string tmp2 = tmp1.Replace("-", "");            string tmp3 = tmp2.Replace(":", "");            string tempTime = tmp3.Replace(" ", "");            tempTime += "|";            sw.WriteLine("{0}{1}",tempTime,info);        }        public void CloseLog()        {            if (sw != null)            {                sw.Close();                sw = null;            }            if (fs != null)            {                fs.Close();                fs = null;            }        }        public void DeleteFile()        {            try            {                if (!File.Exists(Dir + "\\" + getFileName())) //文件不存在,直接跳过                    return;                DateTime createTime = File.GetLastWriteTime(Dir + "\\" + getFileName());//获取文件的最后修改时间,如果获取文件的最后创建时间,会有问题                DateTime nowTime = DateTime.Now;                //删除文件                if ((createTime.Year != nowTime.Year) && (createTime.Month == nowTime.Month))                {                    File.Delete(Dir + "\\" + getFileName());                }            }            catch (System.Exception ex)            {                WriteLog("删除日志文件:" + getFileName() + "失败。失败原因:"+ex.Message);            }        }    }

      在刚开始做的时候,想法是根据log的创建时间,比较当前的年份和这log的年份,如果年份不相等并且月份相等,我就把这个log删除,比较代码如下:
      if ((createTime.Year != nowTime.Year) && (createTime.Month == nowTime.Month))
   
       这里就出现一个怪异的现象,当我删除这个log文件的时候,再次创建,发现这个创建文件的创建时间仍为上次删除log的创建时间。所以我上面取文件的创建时间比较方法宣告失败(这是我测试好久才发现的,测试了好久一直认为是写的代码问题)。
       你可以做个试验:在桌面上创建一个文件“1.txt”,然后删除它(你可以尝试删除的时候加shift键),随后再创建“1.txt”,看看这个文件的创建时间是不是和刚才删除的文件的创建时间一样。
        这样可以得出一个结论:在我们删除一个文件时(我只在windows操作系统上测试),只是让操作系统认为文件不存在,文件在磁盘上的空间被标记为空,以便再次使用,但是文件的数据没有被移除。
        如果你想真正的删除文件,用.Net你可以参考:http://www.codeproject.com/Articles/22736/Securely-Delete-a-File-using-NET
        这个实现起来类似于从磁盘中查找到此文件所在扇区位置,然后往这些扇区中写入垃圾数据,让原来存文件的扇区数据不完整,这样再次创建文件的时候,只能新创建一个文件,原来存在索引的文件已经被破坏。(类似于我们使用磁盘恢复工具查找我们删除的文件,但是有的文件已经破坏的原理)
   
        因此,从上面的代码中,我换了一种思路,采用文件的修改时间来实现了我的功能。


   
   //记录自己工作学习中的点点滴滴,希望有一天会变强大///

      

原创粉丝点击