我正在学习编写程序来删除超过指定天数的服务器上的日志文件。该程序将基于表而不是基于服务器。使用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
}
答案 0 :(得分: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
}
答案 1 :(得分: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);
}
会打印每个目录中的文件数。