如何将数据库大小从兆字节转换为字节,反之亦然?

时间:2012-09-24 15:07:35

标签: c# asp.net byte megabyte

基本上我正在创建一个复制应用程序,我只需要弄清楚D:\驱动器上可用的数据库大小和可用空间。

如果数据库大小大于可用空间,那么我需要提醒用户。

这是我到目前为止所做的:

首先,我找出D驱动器中有多少可用空间。

DriveInfo di = new DriveInfo(@"D:\");

if (di.IsReady)
{
    freeSpace = di.TotalFreeSpace;
}

然后我得到了我要复制的数据库的大小:

dbSize = Database.GetDatabaseSize(ddlPublisherServer.Text, ddlPublisherDatabase.Text);

这是获取数据库大小的方法。我不知道是否有更好的方法可以做到这一点,但是大小带有“MB”字符串,所以我需要删除它。

public static long GetDatabaseSize(string server, string database)
{
     string finalConnString = Properties.Settings.Default.rawConnectionString.Replace("<<DATA_SOURCE>>", server).Replace("<<INITIAL_CATALOG>>", database);

      using (SqlConnection conn = new SqlConnection(finalConnString))
      {
          using (SqlCommand cmd = new SqlCommand("sp_spaceused", conn))
          {
              cmd.CommandType = CommandType.StoredProcedure;

              conn.Open();
              cmd.ExecuteNonQuery();

              using (SqlDataAdapter da = new SqlDataAdapter(cmd))
              {
                  using (DataSet ds = new DataSet())
                  {
                      da.Fill(ds);

                      var spaceAvailable = ds.Tables[0].Rows[0][1].ToString();

                      string freeSpace = spaceAvailable.Remove(spaceAvailable.Length - 3, 3);

                      return Convert.ToInt64(freeSpace);
                   }
              }
         }
     }
}

我现在的问题是 -

如何将字节转换为兆字节,以便比较db大小和磁盘可用空间?

这就是我所拥有的,但它是超级字节和字节,所以我需要在这里进行转换。

if (dbSize > freeSpace)
{
     ClientScript.RegisterStartupScript(this.GetType(), "Insufficient Space", "alert('The database size is greater than the available space on the drive. Please make some room for the database in D drive of the subscriber server.');", true);
 }

2 个答案:

答案 0 :(得分:6)

字节数到兆字节= Bytes / (1024 * 1024)
兆字节到字节= Megabytes * (1024 * 1024.0)

请务必考虑整数除法,因此1024.0会使用浮点数。

答案 1 :(得分:0)

一千字节有1024字节,兆字节有1024千字节。所以将你的兆字节数乘以1024 * 1024(以获取字节数)。或者将你的字节除以1024 * 1024(以获得兆字节)。