SIN@SAPPOROWORKSの覚書

C#を中心に、夜な夜な試行錯誤したコードの記録です。

ワークグループ・コンピュータ名の取得 (C#)(F#)

ワークグループや、コンピュータ名を取得するには、netapi32.dllのNetWkstaGetInfo()を使用します。
※NetWkstaGetInfoで取得したデータ(構造体)は、システムが割り当てた領域であるため<
NetApiBufferFree()で解放する必要がある

C#サンプル

using System;
using System.Runtime.InteropServices;
namespace Example {
    class Program {
        [StructLayout(LayoutKind.Sequential)]
        struct WKSTA_INFO_100{
            public int platform_id;
            [MarshalAs(UnmanagedType.LPWStr)]
             public string computername;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string langroup;
            public int ver_major;
            public int ver_minor;
        }

        [DllImport("netapi32.dll", CharSet = CharSet.Auto)]
        public extern static int NetWkstaGetInfo( string servername, int level, out IntPtr bufptr );

        [DllImport("netapi32.dll")]
        public extern static int NetApiBufferFree( IntPtr bufptr );

        static void Main(string[] args) {
            IntPtr p = IntPtr.Zero;
            if (0 == NetWkstaGetInfo(null, 100, out p)) {
                 var info = (WKSTA_INFO_100)Marshal.PtrToStructure(p, typeof(WKSTA_INFO_100));
                Console.WriteLine(string.Format("ワークグループ:{0}",info.langroup));
                Console.WriteLine(string.Format("コンピュータ:{0}", info.computername));
                 Console.WriteLine(string.Format("OSバージョン:{0}.{1}",
                                                        info.ver_major,info.ver_minor));
                NetApiBufferFree(p);
            }
            Console.WriteLine();
            Console.WriteLine("何かのキーを押してください。");
            Console.ReadKey();
        }
    }
}

F#サンプル

open System
open System.Runtime.InteropServices

[&lt;StructLayout(LayoutKind.Sequential)>]
type WKSTA_INFO_100 = 
    struct
        val platform_id : int
        [&lt;MarshalAs(UnmanagedType.LPWStr)>]
        val computername : string
        [&lt;MarshalAs(UnmanagedType.LPWStr)>]
        val langroup : string
        val ver_major : int
        val ver_minor : int
    end

[&lt;DllImport("netapi32.dll")>]
extern int NetWkstaGetInfo(
    [&lt;MarshalAs(UnmanagedType.LPWStr)>]String servername,int level,IntPtr * bufptr)

[&lt;DllImport("netapi32.dll")>]  
extern int NetApiBufferFree(IntPtr bufptr)

let servername = null
let mutable p = IntPtr.Zero

let result = NetWkstaGetInfo(servername, 100 , &&p)
if result = 0 then
    let info = Marshal.PtrToStructure(p,typeof&lt;WKSTA_INFO_100>) :?> WKSTA_INFO_100
    printfn "ワークグループ:%s" info.langroup
    printfn "コンピュータ:%s" info.computername
    printfn "OSバージョン:%d.%d"  info.ver_major info.ver_minor
    NetApiBufferFree(p);|>ignore

printfn "何かのキーを押してください。"
Console.ReadKey() |> ignore