Skip to content

Instantly share code, notes, and snippets.

@latkin
Created February 22, 2016 19:46
Show Gist options
  • Save latkin/8ed12eba885d9188d509 to your computer and use it in GitHub Desktop.
Save latkin/8ed12eba885d9188d509 to your computer and use it in GitHub Desktop.
F# p/invoke example with structs
namespace Test
open System.Runtime.InteropServices
// F# implementation of http://pinvoke.net/default.aspx/mpr.WNetAddConnection2
module NativeMethods =
type ResourceScope =
| Connected = 0x1u
| GlobalNet = 0x2u
| Remembered = 0x3u
| Recent = 0x4u
| Context = 0x5u
type ResourceType =
| Any = 0x0u
| Disk = 0x1u
| Print = 0x2u
| Reserved = 0x8u
| Unknown = 0xffffffffu
type ResourceDisplayType =
| Generic = 0x0u
| Domain = 0x1u
| Server = 0x2u
| Share = 0x3u
| File = 0x4u
| Group = 0x5u
| Network = 0x6u
| Root = 0x7u
| ShareAdmin = 0x8u
| Directory = 0x9u
| Tree = 0xau
| NDSContainer = 0xbu
type ResourceUsage =
| Connectable = 0x1u
| Container = 0x2u
| NoLocalDevice = 0x4u
| Sibling = 0x8u
| Attached = 0x10u
| All = 0x13u
| Reserved = 0x80000000u
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type NetResource =
val mutable dwScope : ResourceScope
val mutable dwType : ResourceType
val mutable dwDisplayType : ResourceDisplayType
val mutable dwUsage : ResourceUsage
val mutable lpLocalName : string
val mutable lpRemoteName : string
val mutable lpComment : string
val mutable lpProvider : string
[<DllImport("mpr.dll")>]
extern int WNetAddConnection2(NetResource& netResource, string password, string username, uint32 flags)
open System.Net
type ConnectionInfo =
{ ComputerName : string
Username : string
Password : string }
member __.NetworkCredential = NetworkCredential(__.Username, __.Password)
// programmatic "net use \\computer\c$", more or less
let getConnection connInfo =
match connInfo.ComputerName with
| "localhost" | "." -> ()
| cn ->
let mutable nr =
NetResource(
lpRemoteName = sprintf @"\\%s\C$" cn,
dwType = ResourceType.Disk,
dwScope = ResourceScope.GlobalNet,
dwDisplayType = ResourceDisplayType.Share,
dwUsage = ResourceUsage.Connectable)
match NativeMethods.WNetAddConnection2(&nr, connInfo.Password, connInfo.Username, 0u) with
| 0 -> ()
| hr -> failwithf "unable to connect: %O" (Win32Exception(hr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment