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.
If the database size is larger than the free space, then I need to alert the user.
This is what I have so far:
First I find out how much free space there is in the D drive.
DriveInfo di = new DriveInfo(@"D:\");
if (di.IsReady)
{
freeSpace = di.TotalFreeSpace;
}
Then I get the size of the database I'm going to replicate:
dbSize = Database.GetDatabaseSize(ddlPublisherServer.Text, ddlPublisherDatabase.Text);
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.
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);
}
}
}
}
}
My question now is -
How do I go about converting bytes to mega bytes so I can compare the db size and the disk free space?
This is what I have but it's mega bytes and bytes so I need to do a conversion here.
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);
}
Bytes to Megabytes = Bytes / (1024 * 1024)
Megabytes to Bytes = Megabytes * (1024 * 1024.0)
Be sure to account for integer division, thus the 1024.0
so a floating point number is used.