Share via


How to programmatically access NFS share using Windows API

Recently, we got a case where the customer wanted to programmatically access NFS share using Windows API.

We have an API “WNetAddConnection2” which can be used programmatically for accessing NFS share. So we tested and wrote a code for the customer using this API to mount the NFS share.

The usage of the code is: (where username and Password are optional)

TestWNetAddConnection2.exe <Local Drive Name> <Remote Name> <User Name - optional> <Password - optional>

Example:

TestWNetAddConnection2.exe X: xxx.xx.xxx.xx:/nfsshare

Code: You would need to build the code according to your environment.

/*++

THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF

ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED

TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A

PARTICULAR PURPOSE.

Copyright (C) 2010. Microsoft Corporation. All rights reserved.

*/

#pragma comment(lib, "mpr.lib")

#define NAME 100

#include "stdafx.h"

#include <windows.h>

#include <tchar.h>

#include <stdio.h>

#include <Winnetwk.h>

// Need to link with Netapi32.lib and Mpr.lib

int wmain(int argc, wchar_t * argv[])

{

    DWORD dwRetVal;

    NETRESOURCE nr;

    DWORD dwFlags;

    TCHAR szUserName[NAME] = L"", szPassword[NAME] = L"";

    if(argc < 3)

    {

        printf("Usage: %ls <Local Drive Name> <Remote Name> <User Name - optional> <Password - optional>", argv[0]);

        exit(1);

    }

    // Zero out the NETRESOURCE struct

    memset(&nr, 0, sizeof (NETRESOURCE));

    if(argc > 3)

    {

        // Assuming you have provided the user name and password.

        wcscpy_s(szUserName, NAME, argv[3]);

        wcscpy_s(szPassword, NAME, argv[4]);

    }

    // Assign our values to the NETRESOURCE structure.

    nr.dwScope = RESOURCE_GLOBALNET;

    nr.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;

    nr.dwUsage = RESOURCEUSAGE_CONNECTABLE;

    nr.dwType = RESOURCETYPE_DISK;

    nr.lpRemoteName = argv[2];

    nr.lpLocalName = argv[1];

    nr.lpProvider = L"NFS Network";

    // Assign a value to the connection options

    dwFlags = CONNECT_INTERACTIVE;

    //

    // Call the WNetAddConnection2 function to assign

    // a drive letter to the share.

    //

    dwRetVal = WNetAddConnection2(&nr, szPassword, szUserName, dwFlags);

    //

    // If the call succeeds, inform the user; otherwise,

    // print the error.

    //

    if (dwRetVal == NO_ERROR)

    {

        wprintf(L"Connection added to %s\n", nr.lpRemoteName);

    }

    else

    {

        wprintf(L"WNetAddConnection2 failed with error: %u\n", dwRetVal);

    }

    return 0;

}