Tuesday, February 15, 2011

how to convert bytes in kb,mb and gb in fileupload

take a button,fileupload and a label in designingtime

protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string format = System.DateTime.Now.ToLongDateString() +","+ System.DateTime.Now.ToLongTimeString();

            int size = FileUpload1.FileBytes.Length;
            Label1.Text = FormatBytes(size);

       
        }

      
    }

public string FormatBytes(int Bytes)
    {
        string filesize;
        if (Bytes >= 1073741824)
        {
            decimal size = decimal.Divide(Bytes, 1073741824);
            filesize = string.Format("{0:##.##} GB", size);
        }
        else if (Bytes >= 1048576)
        {
            decimal size = decimal.Divide(Bytes, 1048576);
            filesize = string.Format("{0:##.##} MB", size);
        }
        else if (Bytes >= 1024)
        {
            decimal size = decimal.Divide(Bytes, 1024);
            filesize = string.Format("{0:##.##} KB", size);
        }
        else if (Bytes > 0 & Bytes < 1024)
        {
            decimal size = Bytes;
            filesize = string.Format("{0:##.##} Bytes", size);
        }
        else
        {
            filesize = "0 Bytes";
        }
        return filesize;
    }


You have to add in web.configuration also--

<system.web>
        <httpRuntime  maxRequestLength="2097151" executionTimeout="360"/>
</system.web>







No comments:

Post a Comment