views:

724

answers:

3

I have the following code:

foreach (string p in dirs)
        {
            string path = p;
            string lastAccessTime = File.GetLastAccessTime(path).ToString();
            bool DirFile = File.Exists(path);
            FileInfo fInf = new FileInfo(path);

            DateTime lastWriteTime = File.GetLastWriteTime(p);
            dirFiles.Add(p + "|" + lastAccessTime.ToString() + "|" + DirFile.ToString() + "|" + lastWriteTime.ToString() + "|" + fInf.Length.ToString());


        }

I have a fInf.Length.ToString() and i'd like to measure the output in terms of kbs. Any ideas on how do accomplish this? For example, instead of getting 2048 as a File Size, i'd like to just get 2Kb.

Thanks in advance for help

+2  A: 

If you want the length as a (long) integer:

long lengthInK = fInf.Length / 1024;
string forDisplay = lengthInK.ToString("N0") + " KB";    // eg, "48,393 KB"

If you want the length as a floating point:

float lengthInK = fInf.Length / 1024f;
string forDisplay = lengthInK.ToString("N2") + " KB";    // eg, "48,393.68 KB"
LukeH
+1  A: 

string sizeInKb = string.Format("{0} kb", fileInfo.Length / 1024);

Juanma
+3  A: 

Here's how to get it broken down in gigabytes, megabytes or kilobytes:

string sLen = fInf.Length.ToString();
if (fInf.Length >= (1 << 30))
    sLen = string.Format("{0}Gb", fInf.Length >> 30);
else
if (fInf.Length >= (1 << 20))
    sLen = string.Format("{0}Mb", fInf.Length >> 20);
else
if (fInf.Length >= (1 << 10))
    sLen = string.Format("{0}Kb", fInf.Length >> 10);

sLen will have your answer. You could wrap it in a function and just pass in the Length, or even the FileInfo object.

If instead of 'real' kilobytes, you wanted it in terms of 1000's of bytes, you could replace 1 << 10 and >> 10 with 1000 and /1000 respectively, and similarly for the others using 1000000 and 1000000000.

lavinio