1

我正在学习编写一个程序来删除服务器上超过指定日期的日志文件。该程序将基于表而不是基于服务器。使用 UNC,日志文件目录的路径存储在数据库中。我正在学习 Directory.GetFiles() 方法,但我不确定路径的语法是什么。我认为它将是 workList 因为它存储路径。任何解决此问题的帮助将不胜感激。我的代码如下。

//create list to store database contents
static List<LogData> GetWorkList()
{
    List<LogData> logDatas = new List<LogData>();
    LogData logData = new LogData();


    //execute sql query
    //execute database reader
    string sqlQuery = "Select daysToKeep, fileLocation, active from dbo.FileDeletion where fileLocation='@fileLocation';";
    SqlCommand command = new SqlCommand(sqlQuery);
    SqlDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {

        //make a logData, creating a new instance of a class
        logData = new LogData();

        //move stuff from reader into log data, and exp
        logData.DaysToKeep = Convert.ToInt32(reader["daysToKeep"]);
        logData.Active = Convert.ToBoolean(reader["active"]);
        logData.FileLocation = Convert.ToString(reader["fileLocation"]);


        //add logData to list
        logDatas.Add(logData);

    }

    return logDatas;
}

//Get active entries from table, call getWorkList
public static void WorkList(//Not sure of what path to use)
{   
    //get active entries

    List<LogData> workList = GetWorkList();

    foreach()
    {
        if(File.Exists()
        {

        }
    }

    //check to see if date created in directory is older that x number of days
    if(DateTime.Now.Subtract(dt).TotalDays <= 1)
    {
        log.Info("This directory is less than a day old");
    }
    //if file is older than x number of days
    else if (DateTime.Now.Subtract(dt).TotalDays <= //not sure of what variable or property to use)
    {
        File.Delete
    }
    //delete file
}
4

2 回答 2

2

假设您的 fileLocation 不仅包含路径,还包含文件名,那么下面应该可以工作。

//Get active entries from table, call getWorkList
public static void WorkList(//Not sure of what path to use)
{   
//get active entries

List<LogData> workList = GetWorkList();

foreach(var work in workList)
{
    if(File.Exists(work.fileLocation))
    {
        File.Delete(work.fileLocation);
    }
}

//check to see if date created in directory is older that x number of days
if(DateTime.Now.Subtract(dt).TotalDays <= 1)
{
    log.Info("This directory is less than a day old");
}
//if file is older than x number of days
else if (DateTime.Now.Subtract(dt).TotalDays <= //not sure of what variable or property to use)
{
    File.Delete
}
//delete file

}

于 2013-09-11T19:50:50.607 回答
0

我正在学习 Directory.GetFiles() 方法,但我不确定路径的语法是什么。

Directory.GetFiles()看起来很简单。

foreach (var myPath in pathsFromDatabase)
{
  string[] files = Directory.GetFiles(myPath)
  Console.WriteLine("Directory {0} contains {1} files.", myPath, files.Length);
}

将打印每个目录中的文件数。

于 2013-09-11T20:08:39.370 回答