Thursday, 3 January 2013

Get File Size in B/KB/MB/GB/TB in C#

Get File Size in B/KB/MB/GB/TB in C#

Getting File size  for a directory files in a human readable format using C# recursion. 
Same thing can be applied to drive information(i.e:available space, free space and total space)

        String[] sizeArry = new String[] { "Byes", "KB", "MB", "GB" };
        String Get_Size_in_KB_MB_GB(ulong sizebytes, int index)
        {

            if (sizebytes < 1000) return sizebytes + sizeArry[index];

            else return Get_Size_in_KB_MB_GB(sizebytes / 1024, ++index);

        }

                foreach (String szFile in System.IO.Directory.GetFiles(@"c:\windows"))
                {
                    try
                    {
                        FileInfo fi = new FileInfo(szFile);

                        Console.Write("fileName=" + fi.Name +
"Size=" + Get_Size_in_KB_MB_GB((ulong)fi.Length, 0)
);
                    }
                    catch (Exception)
                    {
                    }
                }
Add Reference to System.IO.

OUTPUT:
fileName=59349730.031Size=3KB
fileName=asd.logSize=49Byes
fileName=bfsvc.exeSize=69KB
fileName=bootstat.datSize=66KB
fileName=CSUP.TXTSize=10Byes
fileName=Desktop-fav-icon.icoSize=21KB
fileName=DirectX.logSize=198Byes
fileName=DPINST.LOGSize=12KB
fileName=DtcInstall.logSize=4KB
fileName=explorer.exeSize=2MB
fileName=firstboot.datSize=0Byes
fileName=fveupdate.exeSize=15KB
fileName=Google Chrome.lnkSize=1KB
fileName=HelpPane.exeSize=716KB
fileName=hh.exeSize=16KB
fileName=HomeBasic.xmlSize=47KB
fileName=iis7.logSize=52KB
fileName=Lenovo telephony.icoSize=21KB
fileName=MEMORY.DMPSize=596MB
fileName=MFGCLEAN.CMDSize=1KB
fileName=mib.binSize=42KB
fileName=msdfmap.iniSize=1KB
fileName=notepad.exeSize=189KB
fileName=ntbtlog.txtSize=199KB
fileName=ODBC.INISize=550Byes
fileName=PFRO.logSize=40KB
fileName=Reg332Unstal.dllSize=209KB
fileName=regedit.exeSize=389KB
fileName=RtlExUpd.dllSize=1MB
fileName=setupact.logSize=82KB
fileName=setuperr.logSize=0Byes
fileName=splwow64.exeSize=65KB
fileName=Starter.xmlSize=47KB
fileName=Synaptics.logSize=1KB
fileName=system.iniSize=219Byes
fileName=TSSysprep.logSize=5KB
fileName=twain.dllSize=92KB
fileName=twain_32.dllSize=50KB
fileName=twunk_16.exeSize=48KB
fileName=twunk_32.exeSize=30KB
fileName=vm332Rmv.iniSize=1KB
fileName=win.iniSize=427Byes
fileName=WindowsShell.ManifestSize=749Byes
fileName=WindowsUpdate.logSize=1MB
fileName=winhlp32.exeSize=9KB
fileName=WLXPGSS.SCRSize=294KB
fileName=WMSysPr9.prxSize=309KB
fileName=write.exeSize=10KB

1 comment: