List files and their properties

List all files and their properties for a given folder in C#.

public void ListFiles()
    try
    {
        String[] files = System.IO.Directory.GetFiles(@"c:Windows", "*", 
	    System.IO.SearchOption.TopDirectoryOnly);
        if (files.Length == 0)
            Console.WriteLine("Empty folder");
        else
        {
 	    foreach (String file in files)
            {
    	        System.IO.FileInfo info = new System.IO.FileInfo(file);
	        String filesize = String.Empty;
	        Int64 size = info.Length;
	        long kb = size / 1024;
	        if (kb > 1024)
	        {
	  	     float mb = kb / 1024;
		     filesize = mb.ToString() + " MB";
	        }
	        else
		    filesize = kb.ToString() + " KB";
 
	        Console.WriteLine(file.Substring(file.LastIndexOf("\") + 1) + " " +
		info.CreationTime.ToString() + " " + info.Attributes.ToString() + 
		" " + filesize);
	    }
        }
    }
    catch (Exception)
    {
        //...
    }
}
Categories: C# Tags: , ,
%d bloggers like this: