How to delete particular files in a directory?

ipjyo
ipjyo used Ask the Experts™
on
Hi,

I have two types of files in a directory as below. Both of them are text files but distinguished by the name prefix "PST" or "SEQ".

PST-051311, PST-051211 etc
SEQ-051311, SEQ-051211, SEQ-051011 etc

I need to look at the directory and for each of those files that start with SEQ, get the date part after the hyphen and if there is no PST file with the same date after the hyphen then delete the SEQ file. In the above example, the file SEQ-051011 should be deleted.

I am looking for some ideas how to do this? Thanks for any ideas.

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
Try this out:
System.IO.DirectoryInfo targetDir = new System.IO.DirectoryInfo(@"C:\some\dir");
System.IO.FileInfo[] pstFiles = targetDir.GetFiles("PST*");
System.IO.FileInfo[] seqFiles = targetDir.GetFiles("SEQ*");

foreach (System.IO.FileInfo seq in seqFiles)
{
    string name = seq.Name.ToLower();
    bool found = false;

    foreach (System.IO.FileInfo pst in pstFiles)
    {
        string tempName = string.Concat("seq", pst.Name.Substring(3).ToLower());

        if (name == tempName)
        {
            found = true;
            break;
        }
    }

    if (!found)
    {
        seq.Delete();
    }
}

Open in new window

Commented:
string[] fileNames = Directory.GetFiles("c:\\dir\\","SEQ-*");
foreach(var fileName in fileNames)
{
   string date = fileName.Substring(4);
   if(!File.Exists(string.Concat(Path.GetDirectoryName(fileName ), "PST-",date)))
   {
      File.Delete(fileName);
   } 
}

Open in new window

Author

Commented:
Thank you very much guys. This is what exactly I need to do in my code.
Both the solutions are working great.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial