Bonjour,

En cherchant sur le net j'ai trouvé une classe pour me connecter à un répertoire réseau:

FileTest.cs
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
 
using System;
using ioFile = System.IO;
using System.Runtime.InteropServices;
 
namespace Consuel.Technical
{
 
	internal class Impersonate 
	{
		//Used in calling WNetAddConnection2
		[StructLayout (LayoutKind.Sequential)]
			public struct NETRESOURCE
		{
			public int dwScope;
			public int dwType;
			public int dwDisplayType;
			public int dwUsage;
			[MarshalAs (UnmanagedType.LPStr)]
			public string lpLocalName;
			[MarshalAs (UnmanagedType.LPStr)]
			public string lpRemoteName;
			[MarshalAs (UnmanagedType.LPStr)]
			public string lpComment;
			[MarshalAs (UnmanagedType.LPStr)]
			public string lpProvider;
		}
		//WIN32API - WNetAddConnection2
		[DllImport("mpr.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
		private static extern int WNetAddConnection2A (
			[MarshalAs (UnmanagedType.LPArray)]
			NETRESOURCE [] lpNetResource
			, 
			[MarshalAs (UnmanagedType.LPStr)]
			string lpPassword
			, 
			[MarshalAs (UnmanagedType.LPStr)]
			string lpUserName
			, 
			int dwFlags
			);
		//WIN32API - WNetCancelConnection2
		[DllImport("mpr.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
		private static extern int WNetCancelConnection2A (
			[MarshalAs (UnmanagedType.LPStr)]
			string lpName
			, int dwFlags
			, int fForce
			);
 
		/// Connects to a share as a different user.  If connect fails, throws an Exception.
		public void ConnectAs (string pShare, string pDomain, string pUser, string pPwd)
		{
			int err = 0;
			string sUser = string.Empty;
			if (pDomain.Length < 0)
				sUser = pDomain + "\\" + pUser;
			else
				sUser = pUser;
			int dwFlags = 0;
			NETRESOURCE [] nr = new NETRESOURCE [1];
			nr[0].lpRemoteName = pShare;
			nr[0].lpLocalName = "";  //mLocalName;
			nr[0].dwType = 1;     //disk
			nr[0].dwDisplayType = 0;
			nr[0].dwScope = 0;
			nr[0].dwUsage = 0;
			nr[0].lpComment = "";
			nr[0].lpProvider = "";
			err = WNetAddConnection2A (nr, pPwd, sUser, dwFlags);
			if (err != 0)
				throw new Exception ("Unable to connect to " + pShare 
					+ ".  Error=" + err.ToString());
		}
		public void Disconnect (string pShare )
		{
			const int dwFlags = 0;
			const int ForceDisconnect = 1;
			int err = 0;
			err = WNetCancelConnection2A (pShare, dwFlags, ForceDisconnect);
			if ((err != 0) && (err != 2250)) //2250 = connection does not exist
				throw new Exception ("Unable to disconnect from " + pShare 
					+ ".  Error=" + err.ToString());
		}
	}
 
 
	/// <summary>
	/// classe du framework technique permettant la gestion des fichiers.
	/// </summary>
	public class FileTest
	{
		#region Constructeurs
			/// <summary>
			/// Initialise une nouvelle instance de la classe <see cref="File"/>
			/// </summary>
			public FileTest()
			{}
		#endregion
 
		#region Variables privées
		private string _Login;
		private string _Password;
		private string _DomainName;
		#endregion
 
		#region Propriétés
		/// <summary>
		/// Obtient/Définit le login pour les partages réseaux
		/// </summary>
		public string Login 
		{
			get
			{
				return _Login;
			}
			set
			{
				_Login = value;
			}
		}
		/// <summary>
		/// Obtient/Définit le mot de passe pour les partages réseaux
		/// </summary>
		public string Password 
		{
			get
			{
				return _Password;
			}
			set
			{
				_Password = value;
			}
		}
		/// <summary>
		/// Obtient/Définit le domaine pour les partages réseaux
		/// </summary>
		public string DomainName
		{
			get
			{
				return _DomainName;
			}
			set
			{
				_DomainName = value;
			}
		}
		#endregion
 
		#region Méthodes static
		/// <summary>
		/// Permet de déterminer si le fichier existe
		/// </summary>
		/// <param name="path">Le chemin complet du fichier</param>
		/// <returns>Le résulat de la vérif</returns>
		public static bool Exists(string path)
		{
			return ioFile.File.Exists(path);
		}
		#endregion
 
 
		#region Méthodes de gestions des fichiers
 
		/// <summary>
		/// Permet d'effacer un fichier, déclenche l'exception appropriée au besoin
		/// </summary>
		/// <param name="path">Le chemin complet du fichier à effacer</param>
		/// <returns>Indique si la supression à pu avoir lieu</returns>
		public bool DeleteFile(string path)
		{
			if ( Connect (path) ) 
			{
				// utilisation de 'IsPathValid' au lieu de 'File.Exists' pour
				// déclancher les exceptions appropriées
				if(IsPathValid(path))
				{
					ioFile.File.Delete(path);
				}
				Disconnect (path);
			}
			return true;
		}
 
 
		/// <summary>
		/// Permet de renomer un fichier, déclenche l'exception appropriée au besoin
		/// </summary>
		/// <param name="oldPath">Le chemin complet du fichier à renomer</param>
		/// <param name="newFileName">Le nouveau nom du fichier, la path d'origine est utilisé
		/// si il n'est pas spécifié</param>
		/// <returns>Indique si le renommage à pu avoir lieu</returns>
		public bool RenameFile(string oldPath, string newFileName)
		{
			if ( Connect (oldPath) && Connect (newFileName)) 
			{	
				// utilisation de 'IsPathValid' au lieu de 'File.Exists' pour
				// déclancher les exceptions appropriées
				if(IsPathValid(oldPath))
				{
					string patch = GetPathWithoutFileName(oldPath);
 
					// si le nouveau nom ne contient pas le path, on y rajoute celui de l'ancien
					if(GetPathWithoutFileName(newFileName) == String.Empty)
					{
						newFileName = patch + newFileName;
					}
 
					ioFile.File.Move(oldPath, newFileName);
				}
				Disconnect (oldPath);
				Disconnect (newFileName);
			}
			return true;
		}
 
 
		/// <summary>
		/// Permet de copier un fichier, déclenche l'exception appropriée au besoin
		/// </summary>
		/// <param name="oldPath">Le chemin complet du fichier à copier</param>
		/// <param name="newPath">Le chemin complet du nouveau fichier, 
		/// utilise le nom du fichier d'origine si pas spécifié</param>
		/// <returns>Indique si la copie à pu avoir lieu</returns>
		public bool CopyFile(string oldPath, string newPath)
		{
			if ( Connect (oldPath) && Connect (newPath)) 
			{
				// utilisation de 'IsPathValid' au lieu de 'File.Exists' pour
				// déclancher les exceptions appropriées
				if(IsPathValid(oldPath) && IsPathValid(newPath))
				{
					string patch = GetPathWithoutFileName(oldPath);
 
					// si le fichier de destination n'est pas préciser, on utilise celui de la source
					if(ioFile.Path.GetFileName(newPath) == String.Empty)
					{
						newPath += ioFile.Path.GetFileName(oldPath);
					}
 
					ioFile.File.Copy(oldPath, newPath);
				}
				Disconnect (oldPath);
				Disconnect (newPath);
			}
			return true;
		}
 
 
		/// <summary>
		/// Permet de déplacer un fichier, déclenche l'exception appropriée au besoin
		/// </summary>
		/// <param name="oldPath">Le chemin complet du fichier à déplacer</param>
		/// <param name="newPath">Le chemin complet du nouveau fichier, 
		/// utilise le nom du fichier d'origine si pas spécifié</param>
		/// <returns>Indique si le déplacement à pu avoir lieu</returns>
		public bool MoveFile(string oldPath, string newPath)
		{
			if ( Connect (oldPath) && Connect (newPath) ) 
			{
				// utilisation de 'IsPathValid' au lieu de 'File.Exists' pour
				// déclancher les exceptions appropriées
				if(IsPathValid(oldPath) && IsPathValid(newPath))
				{
					string patch = GetPathWithoutFileName(oldPath);
 
					// si le fichier de destination n'est pas préciser, on utilise celui de la source
					if(ioFile.Path.GetFileName(newPath) == String.Empty)
					{
						newPath += ioFile.Path.GetFileName(oldPath);
					}
 
					ioFile.File.Move(oldPath, newPath);
				}
				Disconnect (oldPath);
				Disconnect (newPath);
			}
			return true;
		}
 
 
		#endregion
 
		#region Méthodes de gestions des répertoires
 
		/// <summary>
		/// Crée un répertoire, déclenche l'exception appropriée au besoin
		/// </summary>
		/// <param name="path">Chemin complet du répertoire à créer</param>
		/// <returns>Indique si la création à eu lieu</returns>
		public bool CreateFolder(string path)
		{
			if ( Connect (path) ) 
			{
				ioFile.Directory.CreateDirectory(path);
				Disconnect (path);
			}
			return true;
		}
 
 
		/// <summary>
		/// Efface un répertoire, déclenche l'exception appropriée au besoin
		/// </summary>
		/// <param name="path">Chemin complet du répertoire à effacer</param>
		/// <param name="recursive">Indique si la suppression doit etre recursive</param> 
		/// <returns>Indique si la suppression à eu lieu</returns>
		public bool DeleteFolder(string path, bool recursive)
		{
			if ( Connect (path) ) 
			{
				ioFile.Directory.Delete(path, recursive);
				Disconnect (path);
			}
 
			return true;
		}
 
		/// <summary>
		/// Déplace un répertoire, déclenche l'exception appropriée au besoin
		/// </summary>
		/// <param name="pathOrigine">Chemin complet du répertoire à déplacer</param>
		/// <param name="pathDestination">Chemin complet du répertoire à créer</param>
		/// <returns>Indique si le déplacement à eu lieu</returns>
		public bool MoveFolder(string pathOrigine, string pathDestination)
		{
			if ( Connect (pathOrigine) && Connect (pathDestination) ) 
			{
				ioFile.Directory.Move(pathOrigine, pathDestination);
				Disconnect (pathOrigine);
				Disconnect (pathDestination);
			}
			return true;
		}
 
		/// <summary>
		/// Copie un répertoire, déclenche l'exception appropriée au besoin
		/// </summary>
		/// <param name="pathOrigine">Chemin complet du répertoire à copier</param>
		/// <param name="pathDestination">Chemin complet du répertoire à créer</param>
		/// <param name="recusirsive">Indique si la copie doit etre récursive</param>
		/// <returns>Indique si la copie à eu lieu</returns>
		public bool CopyFolder(string pathOrigine, string pathDestination, bool recusirsive)
		{
			if ( Connect (pathOrigine) && Connect (pathDestination) ) 
			{
				CreateFolder(pathDestination);
				foreach (string nameFile in ioFile.Directory.GetFiles(pathOrigine))
				{
					ioFile.File.Copy(new ioFile.FileInfo(nameFile).FullName, pathDestination + "\\" + new ioFile.FileInfo(nameFile).Name);
				}
				if(recusirsive)
				{
					foreach (string nameFolder in ioFile.Directory.GetDirectories(pathOrigine))
					{
						CreateFolder(nameFolder);
						foreach (string nameFile in ioFile.Directory.GetFiles(nameFolder))
						{
							ioFile.File.Copy(new ioFile.FileInfo(nameFile).FullName, pathDestination + "\\" +  new ioFile.FileInfo(nameFile).Name);
						}
					}
				}
				Disconnect (pathOrigine);
				Disconnect (pathDestination);
			}
			return true;
		}
		#endregion
 
		#region méthodes privées
		/// <summary>
		/// Vérifie le path fournit, déclenche l'exception appropriée au besoin
		/// </summary>
		/// <param name="path">Le chemin complet</param>
		/// <returns>Le résulat de la vérif</returns>
		private bool IsPathValid(string path)
		{
			ioFile.Path.GetFullPath(path);
			return true;
		}
 
		/// <summary>
		/// Renvoie l'extention d'un fichier (avec le point)
		/// </summary>
		/// <param name="path">Chemin complet du fichier</param>
		/// <returns>L'extention</returns>
		private string GetExtention(string path)
		{
			return new ioFile.FileInfo(path).Extension;
		}
		/// <summary>
		/// Retour le chemin complet du fichier sans le nom du fichier
		/// </summary>
		/// <param name="path">Chemin complet du fichier</param>
		/// <returns>Chemin complet sans le nom du fichier</returns>
		private string GetPathWithoutFileName(string path)
		{
			return path.Replace(ioFile.Path.GetFileName(path), "");
		}
 
		private bool Connect(string path)
		{
			string server = GetServerName ( path );
			if ( server.Length < 0 && _Login.Length < 0 ) 
			{
				new Impersonate().ConnectAs (server, _DomainName, _Login , _Password);
			}
			return true;
		}
 
		private bool Disconnect(string path)
		{
			string server = GetServerName ( path );
			if ( server.Length < 0 && _Login.Length < 0 ) 
			{
				new Impersonate().Disconnect (server);
			}
			return true;
		}
 
 
		private string GetServerName (string path)
		{
			if (path.Length > 2) 
			{
				if (path.StartsWith (@"\\"))
				{
					return path.Substring (0,path.IndexOf (@"\", 2));
				}
			}
			return string.Empty;
		}
		#endregion
 
 
        internal void ConnectAs()
        {
            throw new NotImplementedException();
        }
    }
}
Form1.cs:

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
 
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Consuel.Technical;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void btRecherche_Click(object sender, EventArgs e)
        {
            FileTest fileNet = new FileTest();
            fileNet.Login = "****";
            fileNet.Password = "******";
            fileNet.DomainName = "CHHF.local";
            fileNet.ConnectAs();
        }
    }
}
J'ai instancié la la classe FileTest mais je n'arrive pas à utiliser la méthode ConnectAS ==> Aucune surcharge pour la méthode ne prend d'argument.


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
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Consuel.Technical;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void btRecherche_Click(object sender, EventArgs e)
        {
            FileTest fileNet = new FileTest();
            fileNet.Login = "****";
            fileNet.Password = "*****";
            fileNet.DomainName = "******";
            fileNet.ConnectAs("","","","");
        }
    }
}
Pouvez-vous m'aider ?

Connaissez vous une autre façon de faire ?

D'avance merci