65.9K
CodeProject is changing. Read more.
Home

Creating network share programmatically

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.97/5 (12 votes)

May 21, 2007

2 min read

viewsIcon

46153

downloadIcon

1024

I have used window api to create the share to the network resource.

Introduction

This article shows the use of the window api to create the share on the network resource. The code snippet firstly check for all the system drives, if it it found the mapped network drive then program simply returns. otherwise it create the network share using the command line arguments supplied to the executable. This is just to demonstrate for creating a mapped drive programmatically.

Using the code

Download & compile the code using the vs2003, now run the executable by supplying the command line parameters to it. i have used the command line parameters to make the program more generic.so that the user of the program simply provide the parameter as he/she required. Please check the command line arguments use as follows

map_drive [username, password, local drive, remote drive]

where username, password is the login credential for the remote system

local drive can be any drive letter other than the drive letter used at local system for example Q:, P: etc.

remote drive is basically the share path which will be mapped to local drive, it should be supplied as follows.

\\ <remote system name> \ <remote directory or drive.>

so lets say the remote system name is admin & the shared directory is songs. so the remote drive parameter could be having the following format.

\\admin\songs

so to sum up all the things...the following command could be used to make network share programmatically

map_drive sysadmin pwd123 X: \\admin\songs.

The following code shows the use of the window api which is responsible creating the above shared network resource.

 NETRESOURCE nr;
 DWORD res;
 
 TCHAR szUserName[MAXLEN];
 TCHAR  szPassword[MAXLEN];
 TCHAR  szLocalName[MAXLEN];
 TCHAR  szRemoteName[MAXLEN];
 
// Assign values to the NETRESOURCE structure.

 nr.dwType = RESOURCETYPE_ANY;
 nr.lpLocalName = szLocalName;
 nr.lpRemoteName = szRemoteName;
 nr.lpProvider = NULL;
//
// Call the WNetAddConnection2 function to assign
//   a drive letter to the share.

 res = WNetAddConnection2(&nr, szPassword, szUserName, FALSE);

Points of Interest

I have used conversion funtion which convert char * to TCHAR *, this basically runs the loop on char* & then typecast each char to TCHAR. currently this is working fine..but there could be another efficient way to do that...i dont know :) if any one know about the other way to do char * to TCHAR * please write to me in feedback.

History

This is just a first release.