You must use PInvoke interface and custom attributes. The following code does what you need. Unfortunately the structure contains strings that must be marshalled explicitly.

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
#light
open System 
open System.Runtime.InteropServices 

//Used in calling WNetAddConnection2 
[<Struct;StructLayout(LayoutKind.Sequential)>] 
type NETRESOURCE = 
  val mutable dwScope: int 
  val mutable dwType: int 
  val mutable dwDisplayType: int 
  val mutable dwUsage: int
  val mutable lpLocalName: nativeint
  val mutable lpRemoteName: nativeint
  val mutable lpComment: nativeint
  val mutable lpProvider: nativeint
  
  new (s, t, d, u, ln, rn, c, p) = {
    dwScope = s
    dwType = t
    dwDisplayType = d
    dwUsage = u
    lpLocalName = ln
    lpRemoteName = rn
    lpComment = c
    lpProvider = p
  }
 
//BOOL WINAPI LogonUserA(LPSTR,LPSTR,LPSTR,DWORD,DWORD,PHANDLE); 
[<DllImport("advapi32.dll")>]
extern bool LogonUserA(string user, string domain, string pwd, int logonType, int logonProvider, IntPtr *token)
[<DllImport("Mpr.dll")>]
extern int WNetAddConnection2A(NETRESOURCE &lpNetResource, string pwd, string user, int dwFlags)
[<DllImport("dbg.dll")>]
extern int fndbg(NETRESOURCE &lpNetResource);

/// Connects to a share as a different user. If connect fails, throws an Exception. 
let ConnectAs (pShare:string,   pLocalName: string, pUser: string, pPwd: string) = 
  let mutable nrt: NETRESOURCE = { 
    lpRemoteName = Marshal.StringToHGlobalAnsi(pShare);
    lpLocalName = Marshal.StringToHGlobalAnsi(pLocalName); //mLocalName; 
    dwType = 1; // RESOURCETYPE_DISK 
    dwDisplayType = 3; // RESOURCEDISPLAYTYPE_SHARE 
    dwScope = 2; // RESOURCE_GLOBALNET 
    dwUsage = 1; // RESOURCEUSAGE_CONNECTABLE 
    lpComment = Marshal.StringToHGlobalAnsi(""); 
    lpProvider = Marshal.StringToHGlobalAnsi("")}
  
  let err = WNetAddConnection2A (&nrt, pPwd, pUser, 0)
  Marshal.FreeHGlobal(nrt.lpComment);
  Marshal.FreeHGlobal(nrt.lpLocalName);
  Marshal.FreeHGlobal(nrt.lpProvider);
  Marshal.FreeHGlobal(nrt.lpRemoteName);
  
  if (err <> 0) then 
    raise (new Exception ("Unable to connect to " ^ pShare ^ ". Error=" ^ err.ToString())) 

ConnectAs("\\\\HOST\\SHARE", "Q:", "USER", "YOUDLIKETOKNOWMYPASSWORD")

Antonio

By on 11/2/2007 10:45 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper