I am writing a service to check my server disk space.
the code are below:
protected override void OnStart(string[] args)
{BackUpDispSpace();}
protected void BackUpDispSpace()
{
EXESpec = Application.ExecutablePath;
TXTSpec = EXESpec.Substring(0, EXESpec.Length - 3) + "txt";
ConnectionOptions oConn = new ConnectionOptions();
oConn.Username = "Username";
oConn.Password = "Password";
string Drive = "";
string FreeSpace = "";
string TotalSpace = "";
int UsedspacePercent = 0;
string strNameSpace = @"\\localhost\root\cimv2";
try
{
ManagementScope oMs = new ManagementScope(strNameSpace, oConn);
ObjectQuery oQuery = new ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
ManagementObjectCollection oReturnCollection = oSearcher.Get();
foreach (ManagementObject oReturn in oReturnCollection)
{
Drive = oReturn["Name"].ToString();
if (Drive == "H:" || Drive == "I:")
{
FreeSpace = BytesToString(Convert.ToInt64(oReturn["FreeSpace"]));
TotalSpace = BytesToString(Convert.ToInt64(oReturn["Size"]));
long UsedSpace = Convert.ToInt64(oReturn["Size"]) - Convert.ToInt64(oReturn["FreeSpace"]);
UsedspacePercent = Percentval(Convert.ToInt64(oReturn["Size"]), UsedSpace);
if (UsedspacePercent >= 60)
{
string Subject = "BackUp Drive(" + Drive + ") Is Allmost Full(" + UsedspacePercent + " % Used).";
string Body = BodyDiskSpace("localhost", Drive, FreeSpace);
MailService.SendMail("pratyushbiswal2008@gmail.com", Subject, Body);
}
}
}
}
catch (Exception ex)
{
;
}
}
my problem is when i was tested this code in my window form level it was working fine.but when i placed this code in my window service level it showing error.
Error message is:
Error : System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Management.ManagementScope.InitializeGuts(Object o)
at System.Management.ManagementScope.Initialize()
at System.Management.ManagementObjectSearcher.Initialize()
at System.Management.ManagementObjectSearcher.Get()
at DataLogClear.DataLogClear.BackUpDispSpace()
Any one can please help me.Thanks in advance.