Search This Blog

Saturday, December 30, 2017

Checking File & Folder Size with Excel Report - C#

using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CheckingFileSize
{
    class Program
    {
        private static int file_count = 0;
        private static int mbfile_count = 0;
        static int folder_count = 0;
        private static double file_mb_size = 0;
        private static int dir_too_count = 0;
        private static int file_too_count = 0;
        static System.Data.DataTable table = new System.Data.DataTable();

        ///
        /// Get the file count of a given directory recursively.
        ///
        static void Main(string[] args)
        {
            try
            {
                // Here we create a DataTable with four columns.
                table.Columns.Add("File Name", typeof(string));
                table.Columns.Add("File Size", typeof(string));
                table.Columns.Add("File MBSize", typeof(string));
                table.Columns.Add("SizeStatus", typeof(string));
                table.Columns.Add("Status", typeof(string));
                table.Columns.Add("DateTime", typeof(DateTime));
                table.Columns.Add("File Path", typeof(string));
                Console.Write("Please enter folder path : ");
                string FolderPath = Console.ReadLine();
                string dirPath = @"" + FolderPath + "";

                string dirName = Path.GetFileNameWithoutExtension(dirPath);
                Console.WriteLine("Checking all files count-----");
                System.Data.DataTable tableExport = GetSubFolder(dirPath);
                ExportListFromTable(tableExport, dirName + "_AllFileSizeLog");
                Console.WriteLine("---------------------------------------------------");
                Console.WriteLine("Total Files Count ==> {0}", file_count);
                Console.WriteLine("Total folder Count ==> {0}", folder_count);
                Console.WriteLine("---------------------------------------------------");
                Console.WriteLine("Total <100 MB Files Count ==> {0}", mbfile_count);
                Console.WriteLine("---------------------------------------------------");
                Console.WriteLine("dir too big Total Count ==> {0}", dir_too_count);
                Console.WriteLine("Files too big Count ==> {0}", file_too_count);
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.Write("Error : " + ex.Message);
                Console.Write("Trace : " + ex.StackTrace);
            }
        }
        /// <summary>
        /// get folder tree
        /// </summary>
        /// <param name="folder"></param>
        /// <returns></returns>
        static System.Data.DataTable GetSubFolder(string folder)
        {

            if (folder.Length < 255)
            {

                string[] subFolders = Directory.GetDirectories(folder);
                foreach (string subFolder in subFolders)
                {
                    folder_count++;
                    GetSubFolder(subFolder);
                }
                string[] files = Directory.GetFiles(folder); FileInfo fileInfo = null;
                foreach (string file in files)
                {
                     long size = 0; string nameFile = Path.GetFileName(file);
                        if (file.Length < 255)
                        {
                            fileInfo = new FileInfo(file);
                            size = fileInfo.Length;
                            file_mb_size = ConvertBytesToMegabytes(size);
                            if (file_mb_size < 100)
                            {
                                mbfile_count++;
                                table.Rows.Add(nameFile, size, file_mb_size.ToString("0.000"), "<100", "Success", DateTime.Now, file);
                            }
                            else
                            {
                                table.Rows.Add(nameFile, size, file_mb_size.ToString("0.000"), ">100", "Success", DateTime.Now, file);
                            }
                        }
                        //truncate files to 255 characters
                        string truncatedFilename = file;
                        if (truncatedFilename.Length > 255)
                        {
                            file_too_count++;
                            truncatedFilename = truncatedFilename.Substring(0, 255);
                            //replace any single quote in filename with two double quotes
                            truncatedFilename = truncatedFilename.Replace("'", "''");
                            table.Rows.Add(nameFile, size, file_mb_size.ToString("0.000"), "Null", "File Long", DateTime.Now, file);
                        }
                        Console.WriteLine("=>" + file_count + " :" + nameFile);
                 
               
                    file_count++;
                }

            }
            else
            {
                dir_too_count++;
                table.Rows.Add(folder, "0", file_mb_size.ToString("0.000"), "Null", "Folder Long", DateTime.Now, "None");
            }
            return table;
        }
        /// <summary>
        /// bytes to MB
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        static double ConvertBytesToMegabytes(long bytes)
        {
            return (bytes / 1024f) / 1024f;
        }
        /// <summary>
        /// Checking file name char
        /// </summary>
        /// <param name="cleanPath"></param>
        /// <returns></returns>
        private static string cleanPath(string toCleanPath, string replaceWith = "-")
        {
            //get just the filename - can't use Path.GetFileName since the path might be bad! 
            string[] pathParts = toCleanPath.Split(new char[] { '\\' });
            string newFileName = pathParts[pathParts.Length - 1];
            //get just the path 
            string newPath = toCleanPath.Substring(0, toCleanPath.Length - newFileName.Length);
            //clean bad path chars 
            foreach (char badChar in Path.GetInvalidPathChars())
            {
                newPath = newPath.Replace(badChar.ToString(), replaceWith);
            }
            //clean bad filename chars 
            foreach (char badChar in Path.GetInvalidFileNameChars())
            {
                newFileName = newFileName.Replace(badChar.ToString(), replaceWith);
            }
            //remove duplicate "replaceWith" characters. ie: change "test-----file.txt" to "test-file.txt" 
            if (string.IsNullOrWhiteSpace(replaceWith) == false)
            {
                newPath = newPath.Replace(replaceWith.ToString() + replaceWith.ToString(), replaceWith.ToString());
                newFileName = newFileName.Replace(replaceWith.ToString() + replaceWith.ToString(), replaceWith.ToString());
            }
            //return new, clean path: 
            return newPath + newFileName;
        }
        /// <summary>
        /// Export to xls to directory Path
        /// </summary>
        public static void ExportListFromTable(System.Data.DataTable table, string filename)
        {
            DirectoryInfo dir = new DirectoryInfo(@"C:\Reports");
            dir.Create();
            string excelFileName = string.Format(@"C:\Reports\" + filename + "_{0}.xls", DateTime.Now.Ticks.ToString());

            FileInfo file = new FileInfo(excelFileName);
            StreamWriter streamWriter = file.CreateText();

            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
            Table tblListView = new Table();
            tblListView.ID = "_tblListView";

            tblListView.BorderStyle = BorderStyle.Solid;
            tblListView.BorderWidth = Unit.Pixel(1);
            tblListView.GridLines = GridLines.Horizontal;
            tblListView.BorderColor = System.Drawing.Color.LightGreen;
            System.Data.DataView dvListViewData = table.DefaultView;
            if (dvListViewData != null && dvListViewData.Count > 0)
            {
                tblListView.Rows.Add(new TableRow());
                tblListView.Rows[0].BackColor = System.Drawing.Color.LightGreen;
                tblListView.Rows[0].Font.Bold = true;

                for (int i = 0; i < table.Columns.Count; i++)
                {
                    tblListView.Rows[0].Cells.Add(new TableCell());
                    tblListView.Rows[0].Cells[i].Text = table.Columns[i].ToString();
                }

                for (int i = 0; i < dvListViewData.Count; i++)
                {
                    tblListView.Rows.Add(new TableRow());

                    for (int j = 0; j < table.Columns.Count; j++)
                    {
                        tblListView.Rows[i + 1].BorderStyle = BorderStyle.Dotted;
                        tblListView.Rows[i + 1].Cells.Add(new TableCell());
                        tblListView.Rows[i + 1].Cells[j].Text = dvListViewData[i][j].ToString();
                    }
                }
            }
            tblListView.RenderControl(htmlTextWriter);
            streamWriter.Write(stringWriter.ToString());

            htmlTextWriter.Close();
            streamWriter.Close();
            stringWriter.Close();
        }
    }
}


No comments:

Post a Comment