The main target for the streamwriter (in the code below) should only report the directories that were deleted. The directories are deleted if older than whatever the set date is. However the streamwriter is only writing the last directory and not the deleted item(s). I'm pretty new and trying to understand what I'm doing wrong, any help is appreciated.
Program
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>
You're rewriting the file every time you iterate using foreach (DirectoryInfo dir in diArr)
.
Also, without curly braces for your if (dir.LastWriteTime < DateTime.Parse(daysPast))
block, only the next line of code (Directory.Delete(dir.FullName, true);
) will be dependent on that condition, and so the using (StreamWriter sw = new StreamWriter(fileName, false))
will be executed for every directory, hence it is always writing the last file only.
Is it something like this that you need (within the try
block):
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("");
}
This stores your deleted directories in a list, and then writes them to a file after the deleting loop has finished.