title: How do I convert the database size from mega bytes to bytes or vice-versa?
body: <p>Basically I'm creating a replication application and I just need to figure out the database size and how much free space I have available on the D:\ drive.</p>
  
  <p>If the database size is larger than the free space, then I need to alert the user.</p>
  
  <p>This is what I have so far:</p>
  
  <p>First I find out how much free space there is in the D drive.</p>
  
  <pre><code>DriveInfo di = new DriveInfo(@"D:\");
  
  if (di.IsReady)
  {
      freeSpace = di.TotalFreeSpace;
  }
  </code></pre>
  
  <p>Then I get the size of the database I'm going to replicate:</p>
  
  <pre><code>dbSize = Database.GetDatabaseSize(ddlPublisherServer.Text, ddlPublisherDatabase.Text);
  </code></pre>
  
  <p>Here's the method that gets the size of the DB. I don't know if there's a better way to do this but the size comes with the "MB" string in it so I need to remove it.</p>
  
  <pre><code>public static long GetDatabaseSize(string server, string database)
  {
       string finalConnString = Properties.Settings.Default.rawConnectionString.Replace("&lt;&lt;DATA_SOURCE&gt;&gt;", server).Replace("&lt;&lt;INITIAL_CATALOG&gt;&gt;", 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);
                     }
                }
           }
       }
  }
  </code></pre>
  
  <p>My question now is -</p>
  
  <p>How do I go about converting bytes to mega bytes so I can compare the db size and the disk free space?</p>
  
  <p>This is what I have but it's mega bytes and bytes so I need to do a conversion here.</p>
  
  <pre><code>if (dbSize &gt; 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);
   }
  </code></pre>