Hi,
I had to Get/Set env variables of a remote/local computer in my project under given credentials with the help of
ManagementScope.But, Didn't get any proper help and hence posting this one just for other programmers...
private void SetEnvPath(bool isRemote, string MachineName, string _UserName, string _Password, FileInfo fileInfo)
{
ManagementObjectSearcher query = null;
ManagementObjectCollection queryCollection = null;
ConnectionOptions _COption = new ConnectionOptions();
if (isRemote)
{
_COption.Username = _UserName;
_COption.Password = _Password;
_COption.EnablePrivileges = true;
}
try
{
ManagementScope _Scope = new ManagementScope("\\\\" + MachineName + "\\root\\cimv2", _COption);
_Scope.Options.Timeout = TimeSpan.FromSeconds(5);
_Scope.Connect();
ObjectQuery setQuery = new ObjectQuery("SELECT * FROM Win32_Environment WHERE name='Path'");
query = new ManagementObjectSearcher(_Scope, setQuery);
queryCollection = query.Get();
string test = "";
if (queryCollection.Count > 0)
{
foreach (ManagementObject EnvVar in queryCollection)
{
test = EnvVar.GetText(TextFormat.Mof);
if (test.Contains("Path") && !EnvVar["VariableValue"].ToString().Contains(fileInfo.DirectoryName))
{
if (EnvVar["VariableValue"].ToString().EndsWith(";"))
EnvVar["VariableValue"] = (object)(((string)EnvVar["VariableValue"]) + fileInfo.DirectoryName.ToString() + ";");
else
EnvVar["VariableValue"] = (object)(((string)EnvVar["VariableValue"]) + ";" + fileInfo.DirectoryName.ToString() + ";");
EnvVar.Put();
}
}
}
}
catch (Exception ex)
{
}
}
Happy Programming ! !
:laugh:
Mohan Ayyavu,
Senior Software Engineer,
Computer Sciences Corporation, Chennai, India