C # File Deletion Problems

Source: Internet
Author: User

Yesterday, you need to write a program to delete the log file in c. For example, a program of mine needs to have a log. I write the log to the log file, and I automatically create a log file every month. This log file is named like "xxx04.log", where xxx is my project name and 04 represents the log of July.

In terms of log naming, the logs in April of the next year will also be written in the log, which will be confusing and log logs will be very large, so I want to delete the "xxx04.log" log from the next year to the first in April, and then create a new log with the same name ("xxx04.log ").

Paste the code first:

Class RecordLog

[Csharp]
{
Public FileStream fs = null;
Public StreamWriter sw = null;
Public string Dir = @ "D: \ xxx ";
/// <Summary>
/// Read or create a log file
/// </Summary>
Public RecordLog ()
{
Try
{
If (! Directory. Exists (Dir) // The Directory does not exist. Create a Directory
{
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 () // create different log files based on different months
{
DateTime dt = DateTime. Now;
Int month = dt. Month;
String strMonth = (month> 10 )? Month. ToString (): "0" + month. ToString ();

Return "xxx" + strMonth + ". log ";
}
/// <Summary>
/// Write logs
/// </Summary>
/// <Param name = "info"> log information to be written </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 () // The object does not exist and is skipped directly.
Return;
DateTime createTime = File. GetLastWriteTime (Dir + "\" + getFileName (); // get the last modification time of the object. If the last creation time of the object is obtained, the problem may occur.
DateTime nowTime = DateTime. Now;
 
// Delete an object
If (createTime. Year! = NowTime. Year) & (createTime. Month = nowTime. Month ))
{
File. Delete (Dir + "\" + getFileName ());
}
}
Catch (System. Exception ex)
{
WriteLog ("delete Log File:" + getFileName () + "failed. Cause of failure: "+ ex. Message );
}
}
}
At the beginning, the idea was to compare the current year with the log year based on the log creation time. If the year is not equal and the month is equal, I will delete the log, the comparison code is as follows:
If (createTime. Year! = NowTime. Year) & (createTime. Month = nowTime. Month ))

Here is a strange phenomenon. When I delete this log file, I create it again and find that the creation time of this file is still the time when the log was last deleted. Therefore, the method for comparing the creation time of the above file fails to be declared (this was discovered after a long test, and it has been regarded as a write code problem for a long time ).
You can test the file creation time to see if it is the same as the creation time of the deleted file.
In this way, we can draw a conclusion: When we delete a file (I only test it on a windows operating system), we just let the operating system think that the file does not exist, the file space on the disk is marked as null for reuse, but the file data is not removed.
If you want to really delete the file, use. Net you can refer to: http://www.codeproject.com/Articles/22736/Securely-Delete-a-File-using-NET
This implementation is similar to finding the location of the sector where the file is located from the disk, and then writing junk data to these sectors, so that the data in the original sector of the file is incomplete, in this way, only one new file can be created when the file is created again. The file with the original index has been damaged. (Similar to how we use Disk Recovery Tools to find the files we have deleted, but some files have been damaged)

Therefore, in the above code, I changed my mind and implemented my functions using the file modification time.



// Record your work and study progress, hoping to become more powerful one day ///



From richerg85's column

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.