流写器的主要目标(在下面的代码中)应该只报告已删除的目录。如果早于设置日期,则删除目录。但是,流写器只写入最后一个目录而不是已删除的项目。我很新,并试图了解我做错了什么,感谢任何帮助。
程序
using System;
using System.IO;
using System.Configuration;
using System.Text;
public class Program
{
static void Main(string[] args)
{
//number of days from App.config
String daysPast = ConfigurationManager.AppSettings["TimeSpan"];
String path = ConfigurationManager.AppSettings["FilePath"];
// Reference to a directory.
DirectoryInfo di = new DirectoryInfo(path);
// Reference to each directory in that directory.
DirectoryInfo[] diArr = di.GetDirectories();
//StreamWriter file name
string fileName = "fileResults_" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm") + ".txt";
try
{
foreach (DirectoryInfo dir in diArr)
{
if (dir.LastWriteTime < DateTime.Parse(daysPast))
Directory.Delete(dir.FullName, true);
using (StreamWriter sw = new StreamWriter(fileName, false))
{
foreach (DirectoryInfo FilePath in di.GetDirectories())
{
sw.WriteLine("File(s) deleted on: " + DateTime.Now);
sw.WriteLine("============================================");
sw.WriteLine("");
sw.WriteLine(dir.FullName,false);
sw.WriteLine("");
sw.WriteLine("End of list");
sw.WriteLine("");
sw.Flush();
}
}
}
}
catch (InvalidCastException)
{
Console.WriteLine("There was an issue, please try again.");
}
}
}
App.Config中
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="FilePath" value="C:\testFolder\" /><!--root folder -->
<add key="TimeSpan" value="-2.00:00:00"/><!--adjust days -->
</appSettings>
</configuration>
答案 0 :(得分:1)
每次使用foreach (DirectoryInfo dir in diArr)
进行迭代时,都会重写文件。
此外,如果您的if (dir.LastWriteTime < DateTime.Parse(daysPast))
块没有大括号,则只有下一行代码(Directory.Delete(dir.FullName, true);
)将依赖于该条件,因此using (StreamWriter sw = new StreamWriter(fileName, false))
将为每个执行目录,因此它总是只写最后一个文件。
你需要(在try
区块内)是否像这样:
List<string> deletedDirectories = new List<string>();
foreach (DirectoryInfo dir in diArr)
{
if (dir.LastWriteTime < DateTime.Parse(daysPast))
{
Directory.Delete(dir.FullName, true);
deletedDirectories.Add(dir.FullName);
}
}
using (StreamWriter sw = new StreamWriter(fileName, false))
{
sw.WriteLine("File(s) deleted on: " + DateTime.Now);
sw.WriteLine("============================================");
sw.WriteLine("");
foreach (string deletedDirectory in deletedDirectories)
{
sw.WriteLine(deletedDirectory);
}
sw.WriteLine("");
sw.WriteLine("End of list");
sw.WriteLine("");
}
这会将已删除的目录存储在列表中,然后在删除循环结束后将它们写入文件。