Partage de fichiers

Soyez le premier à donner votre avis sur cette source.

Vue 21 209 fois - Téléchargée 527 fois

Description

Ce petit extrait de code permet de créer un partage de fichier sur un ordinateur du réseau. Le code utilise la librairie netapi32.dll avec une version de Windows type NT (NT 4, 2000, 2003 ou XP) ou svrapi.dll avec une version de windows type 9x (95, 98 ou Millénium)

Source / Exemple :


using System;
using System.Runtime.InteropServices;

namespace NetApi32
{
  //Structure pour Getversion
  public struct OSVERSIONINFO
  {
    public int dwOSVersionInfoSize;
    public int dwMajorVersion;
    public int dwMinorVersion;
    public int dwBuildNumber;
    public int dwPlatformId;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
    public string szCSDVersion;
  }
  
  public enum VER_PLATFORM : int
  {
    VER_PLATFORM_WIN32s = 0,
    VER_PLATFORM_WIN32_WINDOWS = 1,
    VER_PLATFORM_WIN32_NT = 2,
  }

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

    
  //Types d'accès
  public enum ACCESS_TYPE : int
  {
    ACCESS_READ = 0x1,
    ACCESS_WRITE = 0x2,
    ACCESS_CREATE = 0x4,
    ACCESS_EXEC = 0x8,
    ACCESS_DELETE = 0x10,
    ACCESS_ATRIB = 0x20,
    ACCESS_PERM = 0x40,
    ACCESS_ALL = 0x7F,
    WNTYPE_DRIVE = 1,
    SHI_USES_UNLIMITED = -1,
  }

  //Structure Info de retour de NetShareAdd
  public enum NET_API_STATUS : uint
  {
    NERR_BASE = 2100,
    NERR_Success = 0,
    NERR_UnknownDevDir = (NERR_BASE + 16),
    NERR_RedirectedPath = (NERR_BASE + 17),
    NERR_DuplicateShare =  (NERR_BASE + 18),
    NERR_BufTooSmall = (NERR_BASE + 23),
    NERR_NetNameNotFound = (NERR_BASE+210),
    NERR_InvalidComputer = (NERR_BASE + 251),
    NERR_DCNotFound = (NERR_BASE + 353),
    ERROR_ACCESS_DENIED = 5,
    ERROR_NOT_ENOUGH_MEMORY = 8,
    ERROR_INVALID_PARAMETER = 87,
    ERROR_INVALID_NAME = 123,
    ERROR_INVALID_LEVEL = 124,
  }

  [ 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;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string shi502_passwd;
    public Int32 shi502_reserved;
    public IntPtr shi502_security_descriptor;
  }

  public struct SHARE_INFO_2
  {
    [MarshalAs(UnmanagedType.LPWStr)]
    public string shi2_netname;
    public uint shi2_type;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string shi2_remark;
    public Int32 shi2_permissions;
    public Int32 shi2_max_uses;
    public Int32 shi2_current_uses;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string shi2_path;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string shi2_passwd;
  }

  public struct SHARE_INFO_50
  {
    [MarshalAs(UnmanagedType.LPWStr)]
    public string shi50_netname;
    public uint shi50_type;
    public Int32 shi50_flags;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string shi50_remark;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string shi50_path;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string shi50_rw_password;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string shi50_ro_password;
  }

  //ACL de Descripteur de Sécurité
  public struct ACL
  {
    public byte AclRevision;
    public byte Sbz1;
    public int AclSize;
    public int AceCount;
    public int Sbz2;
  }

  //Descripteur de Sécurité de SHARE_INFO_502
  public struct SECURITY_DESCRIPTOR
  {
    public byte Revision;
    public byte Sbz1;
    public long Control;
    public long Owner;
    public long Group;
    public ACL Sacl;
    public ACL Dacl;
  }

  public class Share
  {
    //Imports API NT
    [DllImport("Netapi32.dll", EntryPoint="NetShareDel")]
    public static extern long NetShareDelNT([MarshalAs(UnmanagedType.LPWStr)]
      string strServer, [MarshalAs(UnmanagedType.LPWStr)] string netname, Int32 reserved);
    
    [DllImport("Netapi32.dll", EntryPoint="NetShareAdd")]
    public static extern int NetShareAddNT([MarshalAs(UnmanagedType.LPWStr)]
      string strServer, Int32 dwLevel, IntPtr buf, IntPtr parm_err);

    //Imports API 9x
    [DllImport("svrapi.dll", EntryPoint="NetShareDel")]
    public static extern long NetShareDel([MarshalAs(UnmanagedType.LPWStr)]
      string strServer, [MarshalAs(UnmanagedType.LPWStr)] string netname, Int32 reserved);
    
    [DllImport("svrapi.dll", EntryPoint="NetShareAdd")]
    public static extern long NetShareAdd([MarshalAs(UnmanagedType.LPWStr)]
      string strServer, Int32 dwLevel, IntPtr buf, IntPtr parm_err);

    public static NET_API_STATUS CreateShare(string strServer, string strPath, string strShareName, string strShareDesc, bool bAdmin)
    {
      long OS;
      OSVERSIONINFO OSVERInfo = new OSVERSIONINFO();

      OSVERInfo.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFO));
      OS = SystemInfo.GetVersionEx(ref OSVERInfo);

      NET_API_STATUS nRetValue = NET_API_STATUS.NERR_Success;

      if (OSVERInfo.dwPlatformId == (int) VER_PLATFORM.VER_PLATFORM_WIN32_WINDOWS)
      {
        //Système d'exploitation de type Windows 9x
        SHARE_INFO_2 shInfo = new SHARE_INFO_2();
        shInfo.shi2_netname = strShareName;
        shInfo.shi2_type = (uint)SHARE_TYPE.STYPE_DISKTREE;
        if (bAdmin)
        {
          shInfo.shi2_type = (uint)SHARE_TYPE.STYPE_SPECIAL;
          shInfo.shi2_netname += "$";
        }
        shInfo.shi2_permissions = 0;
        shInfo.shi2_path = strPath;
        shInfo.shi2_passwd = null;
        shInfo.shi2_remark = strShareDesc;
        shInfo.shi2_max_uses = -1;

        string strTargetServer = strServer;
        if (strServer.Length != 0)
        {
          strTargetServer = strServer;
          if (strServer[0] != '\\' && strServer[1] != '\\')
          {
            strTargetServer = "\\\\" + strServer;
          }
        }
        // Appel de l'API Net pour ajouter le partage..
        int nStSize = Marshal.SizeOf(shInfo);
        IntPtr buffer = Marshal.AllocCoTaskMem(nStSize);
        Marshal.StructureToPtr(shInfo, buffer, false);
        nRetValue = (NET_API_STATUS) NetShareAdd(strTargetServer, 2, buffer, IntPtr.Zero);
        Marshal.FreeCoTaskMem( buffer );
      }
      else
      {
        //Système d'exploitation de type NT
        SHARE_INFO_502 shInfo = new SHARE_INFO_502();
        shInfo.shi502_netname = strShareName;
        shInfo.shi502_type = (uint)SHARE_TYPE.STYPE_DISKTREE;
        if (bAdmin)
        {
          shInfo.shi502_type = (uint)SHARE_TYPE.STYPE_SPECIAL;
          shInfo.shi502_netname += "$";
        }
        shInfo.shi502_permissions = 0;
        shInfo.shi502_path = strPath;
        shInfo.shi502_passwd = null;
        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] != '\\' && strServer[1] != '\\')
          {
            strTargetServer = "\\\\" + strServer;
          }
        }
        // Appel de l'API Net pour ajouter le partage..
        int nStSize = Marshal.SizeOf(shInfo);
        IntPtr buffer = Marshal.AllocCoTaskMem(nStSize);
        Marshal.StructureToPtr(shInfo, buffer, false);
        nRetValue = (NET_API_STATUS) NetShareAddNT(strTargetServer, 502, buffer, IntPtr.Zero);
        Marshal.FreeCoTaskMem( buffer );
      }
      return nRetValue;
    }
  }

  public class SystemInfo
  {
    [DllImport("kernel32.dll", EntryPoint="GetVersionExA")]
    public static extern long GetVersionEx(ref OSVERSIONINFO lpVersionInformation);
  }
}

Conclusion :


Le Morceau de code suivant partage le répertoire C:\Test de l'ordinateur sur lequel le programme est lancé :

NET_API_STATUS res = Share.CreateShare(Dns.GetHostName(), "C:\\Test", "Test", "Description", false);

if (res == NET_API_STATUS.NERR_Success)
MessageBox.Show ("Partage OK", "Infos !", MessageBoxButtons.OK, MessageBoxIcon.Information);

else if (res == NET_API_STATUS.NERR_DuplicateShare)
MessageBox.Show ("Le partage 'Test' existe déjà.", "Erreur !", MessageBoxButtons.OK, MessageBoxIcon.Error);

Codes Sources

A voir également

Ajouter un commentaire Commentaire
Messages postés
6351
Date d'inscription
samedi 1 juin 2002
Statut
Modérateur
Dernière intervention
2 août 2014
97
Interressant ça, une bonne alternative à WMI
je met en favoris ça risque de servir
merci

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.