IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

[C#] Comment réalise-t-on une copie de fichier avec WMI ?


Sujet :

C#

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    93
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Mars 2004
    Messages : 93
    Points : 61
    Points
    61
    Par défaut [C#] Comment réalise-t-on une copie de fichier avec WMI ?
    Bonjour,

    je voudrais savoir quels sont les moyens de copier des fichiers à travers un réseau en atteignant des chemin du type \\IP\c$\....

    avec System.IO.File.copy le programme doit disposer du droit de copie vers le poste destination.

    y-a t'il un moyen de copier des fichiers vers les postes et spécifier le login et mot de passe par code ?
    (J'ai vaguement entendu parler de WMI, est-ce une solution ?)

    je connai bien sur les login et mots de passe des machines qui recevront ces fichiers.

    J'ai testé la source à la fin du tutorial WMI C# et j'arrive à lister les composants de ma machine locale et distante.

    Quelqu'un sait -il comment on réalise une copie de fichier avec WMI ?

  2. #2
    Membre du Club
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    93
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Mars 2004
    Messages : 93
    Points : 61
    Points
    61
    Par défaut
    j'ai aussi trouvé un soft bien utile : WMI code creator qui permet de générer des code C# C++ ou VB Script.

    mais pour l'instant rien ne fonctionne. au passage, l'outil me génére le code suivant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
     
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.Management;
     
    namespace WMISample
    {
        public class CallWMIMethod : System.Windows.Forms.Form
        {
            private System.Windows.Forms.Label userNameLabel;
            private System.Windows.Forms.TextBox userNameBox;
            private System.Windows.Forms.TextBox passwordBox;
            private System.Windows.Forms.Label passwordLabel;
            private System.Windows.Forms.Button OKButton;
            private System.Windows.Forms.Button cancelButton;
     
            private System.ComponentModel.Container components = null;
     
            public CallWMIMethod()
            {
                InitializeComponent();
            }
     
            protected override void Dispose( bool disposing )
            {
                if( disposing )
                {
                    if (components != null)
                    {
                        components.Dispose();
                    }
                }
                base.Dispose( disposing );
            }
     
            private void InitializeComponent()
            {
                this.userNameLabel = new System.Windows.Forms.Label();
                this.userNameBox = new System.Windows.Forms.TextBox();
                this.passwordBox = new System.Windows.Forms.TextBox();
                this.passwordLabel = new System.Windows.Forms.Label();
                this.OKButton = new System.Windows.Forms.Button();
                this.cancelButton = new System.Windows.Forms.Button();
                this.SuspendLayout();
                // 
                // userNameLabel
                // 
                this.userNameLabel.Location = new System.Drawing.Point(16, 8);
                this.userNameLabel.Name = "userNameLabel";
                this.userNameLabel.Size = new System.Drawing.Size(160, 32);
                this.userNameLabel.TabIndex = 0;
                this.userNameLabel.Text = "Enter the user name for the remote
     computer:";
                // 
                // userNameBox
                // 
                this.userNameBox.Location = new System.Drawing.Point(160,
     16);
                this.userNameBox.Name = "userNameBox";
                this.userNameBox.Size = new System.Drawing.Size(192, 20);
                this.userNameBox.TabIndex = 1;
                this.userNameBox.Text = "";
                // 
                // passwordBox
                // 
                this.passwordBox.Location = new System.Drawing.Point(160, 48);
                this.passwordBox.Name = "passwordBox";
                this.passwordBox.PasswordChar = '*';
                this.passwordBox.Size = new System.Drawing.Size(192, 20);
                this.passwordBox.TabIndex = 3;
                this.passwordBox.Text = "";
                // 
                // passwordLabel
                // 
                this.passwordLabel.Location = new System.Drawing.Point(16,
     48);
                this.passwordLabel.Name = "passwordLabel";
                this.passwordLabel.Size = new System.Drawing.Size(160, 32);
                this.passwordLabel.TabIndex = 2;
                this.passwordLabel.Text = "Enter the password for the remote
     computer:";
                // 
                // OKButton
                // 
                this.OKButton.Location = new System.Drawing.Point(40, 88);
                this.OKButton.Name = "OKButton";
                this.OKButton.Size = new System.Drawing.Size(128, 23);
                this.OKButton.TabIndex = 4;
                this.OKButton.Text = "OK";
                this.OKButton.Click += new System.EventHandler
    (this.OKButton_Click);
                // 
                // cancelButton
                // 
                this.cancelButton.DialogResult =
     System.Windows.Forms.DialogResult.Cancel;
                this.cancelButton.Location = new System.Drawing.Point(200,
     88);
                this.cancelButton.Name = "cancelButton";
                this.cancelButton.Size = new System.Drawing.Size(128, 23);
                this.cancelButton.TabIndex = 5;
                this.cancelButton.Text = "Cancel";
                this.cancelButton.Click += new System.EventHandler
    (this.cancelButton_Click);
                // 
                // MyQuerySample
                // 
                this.AcceptButton = this.OKButton;
                this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                this.CancelButton = this.cancelButton;
                this.ClientSize = new System.Drawing.Size(368, 130);
                this.ControlBox = false;
                this.Controls.Add(this.cancelButton);
                this.Controls.Add(this.OKButton);
                this.Controls.Add(this.passwordBox);
                this.Controls.Add(this.passwordLabel);
                this.Controls.Add(this.userNameBox);
                this.Controls.Add(this.userNameLabel);
                this.Name = "MyQuerySample";
                this.StartPosition =
     System.Windows.Forms.FormStartPosition.CenterScreen;
                this.Text = "Remote Connection";
                this.ResumeLayout(false);
     
            }
     
            [STAThread]
            static void Main() 
            {
                Application.Run(new CallWMIMethod());
            }
     
            private void OKButton_Click(object sender, System.EventArgs e)
            {
                try
                {
                    ConnectionOptions connection = new ConnectionOptions();
                    connection.Username = userNameBox.Text;
                    connection.Password = passwordBox.Text;
                    connection.Authority = "ntlmdomain:***mondomaine***";
     
                    ManagementScope scope = new ManagementScope(
                        "\\\\***monIP***\\root\\CIMV2", connection);
                    scope.Connect();
     
                    ManagementObject classInstance = 
                        new ManagementObject(scope, 
                        new ManagementPath("Win32_Directory.Name='c:\'"),
                        null); //****destination****
     
                    // Obtain in-parameters for the method
                    ManagementBaseObject inParams = 
                        classInstance.GetMethodParameters("CopyEx");
     
                    // Add the input parameters.
                    inParams["FileName"] =  "c:\aaa\test.txt"; //***fichier à
     copier***
     
                    // Execute the method and obtain the return values.
                    ManagementBaseObject outParams = 
                        classInstance.InvokeMethod("CopyEx", inParams, null);
     
                    // List outParams
                    Console.WriteLine("Out parameters:");
                    Console.WriteLine("ReturnValue: " + outParams
    ["ReturnValue"]);
                    Console.WriteLine("StopFileName: " + outParams
    ["StopFileName"]);
     
                    Close();
                }
                catch(ManagementException err)
                {
                    MessageBox.Show("An error occurred while trying to execute
     the WMI method: " + err.Message);
                }
                catch(System.UnauthorizedAccessException unauthorizedErr)
                {
                    MessageBox.Show("Connection error (user name or password
     might be incorrect): " + unauthorizedErr.Message);
                }
            }
     
            private void cancelButton_Click(object sender, System.EventArgs e)
            {
                Close();
            }
        }
    }

  3. #3
    Membre du Club
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    93
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Mars 2004
    Messages : 93
    Points : 61
    Points
    61
    Par défaut
    j'ai trouvé aussi une alternative dans le forum VB.Net pour le sujet copie de fichier avec WMI

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
     
    ProcessStartInfo psi = new ProcessStartInfo("cmd"); 
                    Process p = new Process(); 
                    p.StartInfo = psi;
                    p.Start();                
     
                    SendKeys.Flush();
                    Thread.Sleep(500);
                    SendKeys.SendWait("{ENTER}c:{ENTER}");
                    SendKeys.SendWait("{ENTER}cd \\{ENTER}");
                    DirectoryInfo myDir2 = new DirectoryInfo("z:");
                    if (myDir2.Exists)
                    {
                        SendKeys.SendWait("{ENTER}net use /delete z:{ENTER}");
                    }
                    SendKeys.SendWait("{ENTER}net use z: <a href="http://www.developpez.net/forums/" target="_blank">\\\\1.136.100.12</a>
    \\c${ENTER}");
                    SendKeys.SendWait("{ENTER}z: {ENTER}"); 
                    SendKeys.SendWait("{ENTER}cd \\ {ENTER}"); 
                    SendKeys.SendWait("{ENTER}md InstallationProgramme
    {ENTER}");
                    SendKeys.SendWait("{ENTER}cd InstallationProgramme
    {ENTER}");
                    SendKeys.SendWait("{ENTER}md sub{ENTER}");
                    SendKeys.SendWait("{ENTER}c:{ENTER}");
                    Thread.Sleep(500);
                    DirectoryInfo myDir = new DirectoryInfo
    ("z:\\InstallationProgramme\\");
                    DirectoryInfo myDir3 = new DirectoryInfo
    ("z:\\InstallationProgramme\\sub\\");
                    if ((myDir.GetFiles("*.*")).Length == 0 && (myDir3.GetFiles
    ("*.*")).Length == 0)
                    {
                        SendKeys.SendWait("{ENTER}xcopy /s
     C:\\Inetpub\\wwwroot\\MAJ\\MisesAJour\\051013102320389\\*
     z:\\InstallationProgramme{ENTER}");
                        SendKeys.SendWait("{ENTER}net use /delete z:{ENTER}");
                        SendKeys.SendWait("{ENTER}exit{ENTER}");
                    }
                    else
                    {
                        SendKeys.SendWait("{ENTER}net use /delete z:{ENTER}");
                        SendKeys.SendWait("{ENTER}exit{ENTER}"); 
                    }
    mais le gros gros problème c'est que le focus doit rester sur la fenêtre de commande crée par cette action sinon, le programme va écrire les commande n'importe ou

    l'url du sujet :
    http://www.developpez.net/forums/vie...er=asc&start=0

  4. #4
    Membre du Club
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    93
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Mars 2004
    Messages : 93
    Points : 61
    Points
    61
    Par défaut
    J'ai apporté un petit plus pour ne plus que le programme affiche une sale fenêtre DOS :

    transformer chaque commande (precedemment lancée dans la cmd) en process :

    - il y a d'abord un net use pour créer le mapping (on teste avant la liste des lettres de lecteurs disponible pour le mapping avec une requete WMI)
    - la copie des fichiers
    - le disconnect du lecteur avec net use /delete ....

    La requete WMI
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
     
    // Déterminer le lecteur à mapper
                    ManagementObjectSearcher query = new
     ManagementObjectSearcher("SELECT * From Win32_LogicalDisk ");
                    ManagementObjectCollection queryCollection = query.Get();
     
                    for (int i=97;i<=122;i++)
                    {    
                        lecteur = Convert.ToChar(i);
                        //le nouveau lecteur existe t-il dans les lecteurs
     physiques ?
                        bool isin = false;
                        foreach ( ManagementObject mo in queryCollection) 
                        {
                            if (mo["name"].ToString().ToLower() == lecteur + ":")
                            {
                                isin=true;
                            }
                        }
                        if (!isin)                        
                        {
                            //on teste alors la liste des mapping
                            if (!Directory.Exists(lecteur + ":\\"))
                                break;
                        }
                    }
    Le process de création de lecteur
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    // créer le mapping
                    ProcessStartInfo pi = new ProcessStartInfo();
                    pi.FileName = "net";
                    pi.Arguments = "use " + lecteur + ": \\\\"+ IP + "\\c$ " +
     password + " /user:" + user;
                    pi.WindowStyle =
     System.Diagnostics.ProcessWindowStyle.Hidden;
                    Process p = new Process();
                    p.StartInfo = pi;
                    p.Start();
                    p.WaitForExit();
    et voila, çà fait la même chose, çà n'utilise toujours pas WMI mais çà marche. Tant pis, je laisse à un autre la tâche de comprendre le fonctionnement de WMI pour une copie de fichier entre différentes machines qui ont des comptes user différents...

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. DataGrid : comment conserver la source originale (ou une copie) ?
    Par EyeRobot dans le forum Windows Presentation Foundation
    Réponses: 4
    Dernier message: 19/06/2014, 07h53
  2. Réponses: 1
    Dernier message: 15/09/2008, 10h21
  3. Réponses: 6
    Dernier message: 29/05/2008, 15h02
  4. Forte charge du système lors d'une copie de fichiers
    Par calfater dans le forum Administration système
    Réponses: 5
    Dernier message: 08/01/2007, 17h52
  5. Problème pour faire une copie de fichier.
    Par damien99 dans le forum C++
    Réponses: 1
    Dernier message: 12/02/2006, 16h37

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo