Thursday, July 14, 2016

Read all files from directory and delete specific files after sorting

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;


namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            string folderPath = @"C:\myfiles\XML";
            List<Int64> fileName = new List<Int64>(); int i = 0;
            foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
            {
                string contents = File.ReadAllText(file);
                fileName.Add(Convert.ToInt64(Path.GetFileNameWithoutExtension(file)));
                Console.WriteLine((fileName[i]).ToString());
                i++;
            }
            Console.WriteLine("sorted order");
            fileName.Sort();
            Console.WriteLine("max value : " + fileName.Max());
            for (int j = 0; j < fileName.Count - 1; j++)
            {
                Console.WriteLine(fileName[j].ToString() + ": will be deleted");
                string file_with_path = folderPath + "\\" + fileName[j].ToString() + ".xml";
                Console.WriteLine(file_with_path + ": will be deleted");
                System.IO.File.Delete(file_with_path);
            }
            Console.ReadLine();
        }
    }
}

1 comment:

  1. string folderPath = @"D:\SSISTemp\naiki\temp";
    string filename1 = string.Empty, filename2 = string.Empty, filename3 = string.Empty;
    int flag1 = 0, flag2 = 0, flag3 = 0;
    List fileName = new List(); int i = 0;
    foreach (string file in Directory.GetFiles(folderPath, "*.txt"))
    {

    MessageBox.Show(file);
    if (file.Contains("abc1.123A"))
    flag1 = 1;
    if (file.Contains("abc1.123B"))
    flag2 = 1;
    if (file.Contains("abc1.123C"))
    flag3 = 1;

    }
    MessageBox.Show("flag1:" + flag1);
    MessageBox.Show("flag2:" + flag2);
    MessageBox.Show("flag3:" + flag3);
    Console.ReadLine();

    ReplyDelete