Справочник по C#

    Исходники по языку программирования CSharp

    Удаление приложений с помощью WMI: Справочник по C#

    /
    /
    /
    50 Views


    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Management;
    using System.DirectoryServices;
    using System.Net;
    using System.Collections;
    using System.ServiceProcess;
    using System.Threading;
    using System.IO;
    using System.Globalization;
    
    namespace UninstallProgram
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }
    ArrayList arrProgram = new ArrayList();
    string name,komp;
    processs frmPrg = new processs();
    bool btncan = false;
    
    ManagementScope scope;
    ConnectionOptions options;
    ManagementObjectSearcher searcher;
    ObjectQuery query;
    ManagementObjectCollection queryCollection;
    
    
    
    #region Получение списка приложений
    public void button1_Click(object sender, EventArgs e)
    {
    frmPrg = new processs();
    frmPrg.Owner = this;
    frmPrg.Show();
    this.Cursor = Cursors.WaitCursor;
    
    komp = textBox1.Text;
    backgroundWorker2.RunWorkerAsync();
    }
    private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
    {
    try
    {
    Cleartext();
    clearlist();
    
    frmPrg.unsert_label("Подключение к удаленной машине");
    string sLogin = "";
    string sPassword = "";
    string machine = komp;
    
    options = new ConnectionOptions();
    options.Username = sLogin;
    options.Password = sPassword;
    options.Authority = "ntlmdomain:";
    options.EnablePrivileges = true;
    options.Impersonation = ImpersonationLevel.Impersonate;
    
    scope = new ManagementScope(string.Format(@"\{0}rootCIMV2", machine), options);
    scope.Connect();
    
    if (scope.IsConnected == true)
    {
    frmPrg.unsert_label("Подключено");
    query = new ObjectQuery("SELECT * FROM Win32_Product");
    searcher = new ManagementObjectSearcher(scope, query);
    queryCollection = searcher.Get();
    
    frmPrg.unsert_label("Получение списка ПО");
    foreach (ManagementObject m in queryCollection)
    {
    try
    {
    string[] srvArray = new string[2];
    srvArray[0] = m["Name"].ToString();
    List(m["Name"].ToString());
    srvArray[1] = m["Name"].ToString();
    arrProgram.Add(srvArray);
    }
    catch (Exception)
    { }
    }
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.ToString(), "Получение списка программ", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    }
    
    private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    zakr_ok();
    }
    public void zakr_ok()
    {
    frmPrg.Closed();
    WindowState = FormWindowState.Normal;
    }
    private void Cleartext()
    {
    try
    {
    if (this.InvokeRequired)
    BeginInvoke(new MethodInvoker(delegate
    {
    textEdit1.Text = "";
    textEdit2.Text = "";
    textEdit3.Text = "";
    textEdit4.Text = "";
    }));
    else
    {
    textEdit1.Text = "";
    textEdit2.Text = "";
    textEdit3.Text = "";
    textEdit4.Text = "";
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }
    public void List(string text)
    {
    try
    {
    if (this.InvokeRequired)
    BeginInvoke(new MethodInvoker(delegate
    {
    listBoxControl1.Items.Add(text);
    listBoxControl1.Update();
    }));
    else
    {
    listBoxControl1.Items.Add(text);
    listBoxControl1.Update();
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }
    public void clearlist()
    {
    try
    {
    if (this.InvokeRequired)
    BeginInvoke(new MethodInvoker(delegate
    {
    listBoxControl1.Items.Clear();
    }));
    else
    {
    listBoxControl1.Items.Clear();
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    
    }
    #endregion
    
    #region Получение информации о по
    private void listBoxControl1_DoubleClick(object sender, EventArgs e)
    {
    frmPrg = new processs();
    frmPrg.Owner = this;
    frmPrg.Show();
    
    backgroundWorker3.RunWorkerAsync();
    }
    private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
    {
    try
    {
    frmPrg.unsert_label("Подключение к удаленной машине");
    Cleartext();
    string sLogin = "";
    string sPassword = "";
    string machine = komp;
    
    ManagementScope scope;
    ConnectionOptions options;
    options = new ConnectionOptions();
    options.Authority = "ntlmdomain:";
    options.Username = sLogin;
    options.Password = sPassword;
    options.EnablePrivileges = true;
    options.Impersonation = ImpersonationLevel.Impersonate;
    
    scope = new ManagementScope(string.Format(@"\{0}rootCIMV2", machine), options);
    scope.Connect();
    
    
    if (scope.IsConnected == true)
    {
    frmPrg.unsert_label("Подключение прошло успешно");
    ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Product");
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
    //System.Threading.Thread.Sleep(5000);
    ManagementObjectCollection queryCollection = searcher.Get();
    frmPrg.unsert_label("Получение информации о ПО");
    foreach (ManagementObject m1 in queryCollection)
    {
    
    // Get back the array with the index of the selected ListBox item from the ArrayList
    string[] srvArray = (string[])arrProgram[listBoxControl1.SelectedIndex];
    // If the current service name
    try
    {
    if (m1["Name"].ToString() == srvArray[1])
    {
    if (m1["Caption"] == null) { }
    else
    {
    unsert_text1(m1["Caption"].ToString());
    }
    
    if (m1["IdentifyingNumber"] == null) { }
    else
    {
    unsert_text2(m1["IdentifyingNumber"].ToString());
    }
    
    if (m1["Version"] == null) { }
    else
    {
    unsert_text3(m1["Version"].ToString());
    }
    
    if (m1["InstallDate"] == null) { }
    else
    {
    unsert_text4(m1["InstallDate"].ToString());
    }
    }
    }
    catch (Exception)
    {
    
    }
    }
    }
    btncan=true;
    }
    catch (ManagementException err)
    {
    MessageBox.Show("An error occurred while querying for WMI data: " + err.Message);
    btncan=false;
    }
    catch (System.UnauthorizedAccessException unauthorizedErr)
    {
    MessageBox.Show("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
    btncan=false;
    }
    catch (NullReferenceException ex)
    {
    MessageBox.Show(ex.Message.ToString());
    btncan=false;
    }
    catch (SystemException ex)
    {
    MessageBox.Show(ex.Message.ToString());
    btncan=false;
    }
    
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message.ToString());
    btncan=false;
    }
    }
    
    public void buttoun_cancel(bool text)
    {
    if (textEdit2.Text.Length == 0)
    {
    button2.Enabled = false;
    }
    else
    button2.Enabled = text;
    }
    
    private void backgroundWorker3_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    zakr_ok();
    buttoun_cancel(btncan);
    }
    public void unsert_text1(string text)
    {
    try
    {
    if (this.InvokeRequired)
    BeginInvoke(new MethodInvoker(delegate
    {
    textEdit1.Text = text;
    }));
    else
    {
    textEdit1.Text = text;
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }
    public void unsert_text2(string text)
    {
    try
    {
    if (this.InvokeRequired)
    BeginInvoke(new MethodInvoker(delegate
    {
    textEdit2.Text = text;
    }));
    else
    {
    textEdit2.Text = text;
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }
    public void unsert_text3(string text)
    {
    try
    {
    if (this.InvokeRequired)
    BeginInvoke(new MethodInvoker(delegate
    {
    textEdit3.Text = text;
    }));
    else
    {
    textEdit3.Text = text;
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }
    public void unsert_text4(string text)
    {
    try
    {
    DateTime date = DateTime.ParseExact(text, "yyyyMMdd", CultureInfo.InvariantCulture);
    
    if (this.InvokeRequired)
    BeginInvoke(new MethodInvoker(delegate
    {
    textEdit4.Text = date.ToString("dd.MM.yyyy");
    }));
    else
    {
    textEdit4.Text = date.ToString("dd.MM.yyyy");
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }
    #endregion
    
    #region Удаление приложения
    private void button2_Click(object sender, EventArgs e)
    {
    frmPrg = new processs();
    frmPrg.Owner = this;
    frmPrg.Show();
    
    backgroundWorker4.RunWorkerAsync();
    }
    private void backgroundWorker4_DoWork(object sender, DoWorkEventArgs e)
    {
    try
    {
    frmPrg.unsert_label("Подключение к удаленной машине");
    
    
    string sLogin = "";
    string sPassword = "";
    string machine = komp;
    int i=0;
    ManagementScope scope;
    ConnectionOptions options;
    options = new ConnectionOptions();
    options.Authority = "ntlmdomain:";
    options.Username = sLogin;
    options.Password = sPassword;
    options.EnablePrivileges = true;
    options.Impersonation = ImpersonationLevel.Impersonate;
    
    frmPrg.unsert_label("Подключение к удаленной машине");
    
    scope = new ManagementScope(string.Format(@"\{0}rootCIMV2", machine), options);
    scope.Connect();
    
    if (scope.IsConnected == true)
    {
    frmPrg.unsert_label("Подключение к удаленной машине установлено");
    ManagementObject classInstance = new ManagementObject(scope, new ManagementPath("Win32_Product.IdentifyingNumber='" + textEdit2.Text + "',Name='" + textEdit1.Text + "',Version='" + textEdit3.Text + "'"), null);
    
    // no method in-parameters to define
    
    // Execute the method and obtain the return values.
    frmPrg.unsert_label("Отправка запроса на удаление");
    
    ManagementBaseObject outParams;
    outParams = classInstance.InvokeMethod("Uninstall", null, null);
    
    //buttoun_cancel(false);
    
    frmPrg.unsert_label("Удаление программы " + textEdit1.Text);
    // backgroundWorker1.RunWorkerAsync();
    
    /*  ManagementBaseObject outParams;
    object result = outParams =
    classInstance.InvokeMethod("Uninstall", null, null);
    //buttoun_cancel(false);*/
    
    
    if (outParams["ReturnValue"].ToString() == "0")
    {
    MessageBox.Show("Удаление приложения " + Environment.NewLine
    + textEdit1.Text + " " + textEdit3.Text + Environment.NewLine +
    "прошло успешно",
    "Удаление приложения", MessageBoxButtons.OK, MessageBoxIcon.Information); return;
    }
    }
    /* Proverka:
    ObjectQuery query = new ObjectQuery(
    "SELECT * FROM Win32_Product");
    
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
    
    ManagementObjectCollection queryCollection = searcher.Get();
    
    foreach (ManagementObject m in queryCollection)
    {
    
    if (textEdit1.Text == m["Caption"])
    {
    goto Proverka; break;
    }
    else
    {
    
    MessageBox.Show("Удаление приложения " + Environment.NewLine
    + textEdit1.Text + " " + textEdit3.Text + Environment.NewLine +
    "прошло успешно",
    "Удаление приложения", MessageBoxButtons.OK, MessageBoxIcon.Information); return;
    //zakr_ok();
    }
    }*/
    
    }
    catch (ManagementException err)
    {
    MessageBox.Show("An error occurred while trying to execute the WMI method: " + err.Message);
    
    }
    
    
    /*MessageBox.Show("Превышен таймаут подключения!" + Environment.NewLine+
    "Попробуйте еще раз."
    ,"Подключение к удаленной машине");
    zakr_ok();*/
    }
    private void backgroundWorker4_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    buttoun_cancel(false);
    zakr_ok();
    button1_Click(sender, e);
    }
    #endregion
    
    
    }
    }

    Удаление приложений с помощью WMI: Справочник по C#

    0.00 (0%) 0 votes

    moyadcode13
    • Facebook
    • Twitter
    • Google+
    • Linkedin
    • Pinterest
    moyadcode10
    moyadcode11
    moyadcode9