Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting file size in KB

Tags:

c#

c#-4.0

i am storing file in database in KB. I try to convert file length return by file info to KB as follow.

FileInfo FileVol = new FileInfo(DownloadPath);
int SizeinKB = (int)(FileVol).Length / 1024 ;

If the file size return from DB and the value in Size in KB is equal then only my code allow to install the software from DownloadPath. But i always getting value in Size in KB less than that of value return from DB (always 1 KB). What is wrong with me.

Please help to resolve.

like image 289
jerin Avatar asked Oct 17 '25 08:10

jerin


2 Answers

you can calculate the file size using this method :

static readonly string[] SizeSuffixes =
                  { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

    static string SizeSuffix(Int64 value)
    {
        if (value < 0) { return "-" + SizeSuffix(-value); }

        int i = 0;
        decimal dValue = (decimal)value;
        while (Math.Round(dValue / 1024) >= 1)
        {
            dValue /= 1024;
            i++;
        }

        return string.Format("{0:n1} {1}", dValue, SizeSuffixes[i]);
    }

then after calculating size you can use if - else check to resolve your problem

like image 117
Alina Anjum Avatar answered Oct 18 '25 22:10

Alina Anjum


FileInfo FileVol = new FileInfo(DownloadPath);
string fileLength = FileVol.Length.ToString();
string length = string.Empty;
if (FileVol.Length >= (1 << 10))
  length= string.Format("{0}Kb", FileVol.Length >> 10);

Length=> will result the KB of the file.

like image 28
er_Yasar Avatar answered Oct 18 '25 21:10

er_Yasar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!