Click here to Skip to main content
Click here to Skip to main content

How to create a file share using .NET framework

By , 27 May 2003
 

Introduction

Title of this article says how to create a file share using .NET framework. But if you really get down to bottom of it, there is no class or method in .NET framework that accomplishes this task. This is the time when we take help from PInvoke to call unmanaged Win32 API. The NetApi in Win32 platform provides a rich set of functions that allows us to do network management.

Details

Network Management API provides following functions to manage file shares.

  • NetShareAdd
  • NetShareDel
  • NetShareCheck
  • NetShareGetInfo
  • NetShareSetInfo

The names of these APIs are very self explanatory. They do what their names suggest. In this article we will show how you can use NetShareAdd API to create a new file share on an existing folder in a machine. Following code is a complete example of how you can use this API with PInvoke in .NET framework to create a share.

There are couple of important points in this code that we would like to highlight.

  • SHARE_INFO_502 structure that contains the share information requires that all strings should be Wide Character strings. Therefore it is important that when you define the structure, use MarshalAs attribute to specify that string should be marshalled appropriately as Wide Character type. You can specify the value foe the attribute as UnmanagedType.LPWStr.
  • In SHARE_INFO_502 structure you can specify the permissions by specifying a Security Descriptor that has the required ACL. If you set the value of shi502_security_descriptor variable to 0, then a null DACL is set on the file share meaning that Everybody has full access to this share.

Code

using System;
using System.Diagnostics;
using System.Collections;
using System.Runtime.InteropServices;
using ActiveDs;

namespace ADSI_Net
{
    class NetApi32
    {
        public enum NetError
        {
            NERR_Success = 0,
            NERR_BASE = 2100,
            NERR_UnknownDevDir = (NERR_BASE + 16),
            NERR_DuplicateShare = (NERR_BASE + 18),
            NERR_BufTooSmall = (NERR_BASE + 23),
        }

        public enum SHARE_TYPE : ulong
        {
            STYPE_DISKTREE = 0,
            STYPE_PRINTQ = 1,
            STYPE_DEVICE = 2,
            STYPE_IPC = 3,
            STYPE_SPECIAL = 0x80000000,
        }

        [ StructLayout( LayoutKind.Sequential )]
        public struct SHARE_INFO_502
        {
            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi502_netname;
            public uint shi502_type;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi502_remark;
            public Int32 shi502_permissions;
            public Int32 shi502_max_uses;
            public Int32 shi502_current_uses;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi502_path;
            public IntPtr shi502_passwd;
            public Int32 shi502_reserved;
            public IntPtr shi502_security_descriptor;
        }

        [DllImport("Netapi32.dll")]
        public static extern int NetShareAdd(
                [MarshalAs(UnmanagedType.LPWStr)]
        string strServer, Int32 dwLevel, IntPtr buf, IntPtr parm_err);


    }
    
    class AD_ShareUtil
    {
        [STAThread]
        static void Main(string[] args)
        {
            string strServer = @"HellRaiser";
            string strShareFolder = @"G:\Mp3folder";
            string strShareName = @"MyMP3Share";
            string strShareDesc = @"Share to store MP3 files";
            NetApi32.NetError nRetVal = 0;
            AD_ShareUtil shUtil = new AD_ShareUtil();
            nRetVal = shUtil.CreateShare(strServer, 
              strShareFolder, strShareName, strShareDesc, false);
            if (nRetVal == NetApi32.NetError.NERR_Success)
            {
                Console.WriteLine("Share {0} created", strShareName);
            }
            else if (nRetVal == NetApi32.NetError.NERR_DuplicateShare)
            {
                Console.WriteLine("Share {0} already exists", 
                          strShareName);
            }
        }

        NetApi32.NetError CreateShare(string strServer,
                                      string strPath,
                                      string strShareName,
                                      string strShareDesc,
                                      bool bAdmin)
        {
            NetApi32.SHARE_INFO_502 shInfo = 
                  new ADSI_Net.NetApi32.SHARE_INFO_502();
            shInfo.shi502_netname = strShareName;
            shInfo.shi502_type = 
                (uint)NetApi32.SHARE_TYPE.STYPE_DISKTREE;
            if (bAdmin)
            {
                shInfo.shi502_type = 
                    (uint)NetApi32.SHARE_TYPE.STYPE_SPECIAL;
                shInfo.shi502_netname += "$";
            }
            shInfo.shi502_permissions = 0;
            shInfo.shi502_path = strPath;
            shInfo.shi502_passwd = IntPtr.Zero;
            shInfo.shi502_remark = strShareDesc;
            shInfo.shi502_max_uses = -1;
            shInfo.shi502_security_descriptor = IntPtr.Zero;

            string strTargetServer = strServer;
            if (strServer.Length != 0)
            {
                strTargetServer = strServer;
                if (strServer[0] != '\\')
                {
                    strTargetServer = "\\\\" + strServer;
                }
            }
            int nRetValue = 0;
            // Call Net API to add the share..
            int nStSize = Marshal.SizeOf(shInfo);
            IntPtr buffer = Marshal.AllocCoTaskMem(nStSize);
            Marshal.StructureToPtr(shInfo, buffer, false);
            nRetValue = NetApi32.NetShareAdd(strTargetServer, 502, 
                    buffer, IntPtr.Zero);
            Marshal.FreeCoTaskMem( buffer );

            return (NetApi32.NetError)nRetValue;
        }
    }
}                       
                            

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Softomatix
Web Developer
United States United States
Member
To learn more about us, Please visit us at http://www.netomatix.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionCan I include a modified version of this class in an open source project?memberJimShermerhorn14 Dec '11 - 19:53 
Hi there,
 
This excellent snippet is something I use over and over in .NET development.
 
Do you mind if I include this (with some additions) to a .NET library I am hoping to "Open Source" (MIT license?)
 
Of course, your name and this article will be embedded in the MIT license notice.
 
Cheers,
Shermerhorn
QuestionHow to set permissions for this example [modified]memberGodLessWarrior8 Jun '10 - 6:17 
This took me a long time to figure out so I would like to share it with the community. This will add 'ReadAndExecute' permissions to the everyone account on the newly created share. This has been tested across both WinXP and Win7. I imagine it will work in Vista as well. My additions are in bold.
 
      //shInfo.shi502_security_descriptor = IntPtr.Zero;

      // Create a new directory security object
      DirectorySecurity dirSec = new DirectorySecurity( );
 
      // Portion pulled from: http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/dc841874-b71b-4e1c-9052-06eb4a87d08f
      // Language appropriate 'Everyone' account
      System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier( System.Security.Principal.WellKnownSidType.WorldSid, null );
      System.Security.Principal.NTAccount acct = sid.Translate( typeof( System.Security.Principal.NTAccount ) ) as System.Security.Principal.NTAccount;
      string strEveryoneAccount = acct.ToString( );
 
      // Add the new access rule to the directory security object
      dirSec.AddAccessRule( new FileSystemAccessRule( strEveryoneAccount, FileSystemRights.ReadAndExecute, AccessControlType.Allow ) );
 
      // Copy the new security descriptor to the shInfo structure
      byte[] managedSD = dirSec.GetSecurityDescriptorBinaryForm( );
      int sdSize = Marshal.SizeOf( managedSD[0] ) * managedSD.Length;
      shInfo.shi502_security_descriptor = Marshal.AllocHGlobal( sdSize );
      Marshal.Copy( dirSec.GetSecurityDescriptorBinaryForm( ), 0, shInfo.shi502_security_descriptor, dirSec.GetSecurityDescriptorBinaryForm( ).Length );
 
      string strTargetServer = strServer;
      if ( strServer.Length != 0 )
      {
        strTargetServer = strServer;
        if ( strServer[0] != '\\' )
        {
          strTargetServer = "\\\\" + strServer;
        }
      }
 
      int nRetValue = 0;
      // Call Net API to add the share..
      int nStSize = Marshal.SizeOf( shInfo );
      IntPtr buffer = Marshal.AllocCoTaskMem( nStSize );
      Marshal.StructureToPtr( shInfo, buffer, false );
      nRetValue = NetApi32.NetShareAdd( strTargetServer, 502,
              buffer, IntPtr.Zero );
      Marshal.FreeHGlobal( shInfo.shi502_security_descriptor );
      Marshal.FreeCoTaskMem( buffer );
 
      return ( NetApi32.NetError )nRetValue;

modified on Tuesday, June 8, 2010 12:23 PM

AnswerRe: How to set permissions for this examplememberjazper22 Nov '10 - 2:41 
This solved my permission problem. GREAT example, thank you!
Regards, Jazper

GeneralHeres an example of how to set the share permissions as wellmemberChris128927 May '10 - 5:39 
I noticed you have not gone into how to set the share permissions so just thought I would post a link to my blog post that has an example of how to do this from a a VB.NET app:
http://cjwdev.wordpress.com/2010/05/27/shared-a-folder-and-setting-share-permissions-from-vb-net/
 
Hope someone finds it useful!
Chris
QuestionProblem regarding folder on desktop of Vista MachinememberDDeepali5 Dec '07 - 2:14 
Hi,
"NetShareDel" is not able to remove the sharing of a folder on Desktop of a vista Machine.
It is working fine for other OS like Xp , for other folders on Vista
but not for a folder on Desktop
 
Do anybody have any idea ??
Do help me plz Smile | :)
 
DDeepali

QuestionDelete Share returning 2310 ?susssushilchoudhari24 Nov '04 - 8:55 
Hi,
 
I wrote a corresponding function for NetShareDel. It is failing with error code 2310.
 
Could You please suggest me what would be reason for that !
 
Thanks!
 
Sushil
AnswerRe: Delete Share returning 2310 ?membersushilchoudhari24 Nov '04 - 15:21 
It seems that the API is not able to find the correct share name. even though it exists.
 
Any suggestions ?
AnswerRe: Delete Share returning 2310 ?sussAmar K. Velmala14 Apr '05 - 3:18 
Hi Sushil
 
If you doesn't have the Share with the name which you are trying to delete then it will return error code: 2310.
 
You can delete an existing share using following declaration.
 
[DllImport("Netapi32.dll")]
public static extern bool NetShareDel([MarshalAs(UnmanagedType.LPWStr)] string strServer, [MarshalAs(UnmanagedType.LPWStr)] string strShareName, int reserved);
 


GeneralUPDATE for VB.Netmembermef52615 Nov '04 - 15:38 
Here's the code in VB.Net:

CNetApi32.vb


QuestionHow about Macintosh Share?memberAVETAR10 Mar '04 - 17:12 
This is a great example, thanks a million. Once thing I would like to know is if this code can be tweaked to add Windows and Macintosh share, and set permissions for both.
 
Thanks if you can shed some light on this.
 
Best Regards,
Ervin.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 28 May 2003
Article Copyright 2003 by Softomatix
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid