Share folder info (netapi32)
class MainConsole
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
struct SHARE_INFO_2
{
[MarshalAs(UnmanagedType.LPWStr)]
public string shi2_netname;
public uint shi2_type;
[MarshalAs(UnmanagedType.LPWStr)]
public string shi2_remark;
public uint shi2_permissions;
public uint shi2_max_uses;
public uint shi2_current_uses;
[MarshalAs(UnmanagedType.LPWStr)]
public string shi2_path;
[MarshalAs(UnmanagedType.LPWStr)]
public string shi2_passwd;
}
static string FormatMessage(int errCode)
{
switch (errCode)
{
case ERROR_ACCESS_DENIED: return "The user does not have access to the requested information.";
case ERROR_INVALID_LEVEL: return "The value specified for the level parameter is invalid.";
case ERROR_INVALID_PARAMETER: return "The specified parameter is invalid.";
case ERROR_MORE_DATA: return "More entries are available. Specify a large enough buffer to receive all entries.";
case ERROR_NOT_ENOUGH_MEMORY: return "Insufficient memory is available.";
case NERR_BufTooSmall: return "The supplied buffer is too small.";
case NERR_NetNameNotFound: return "The share name does not exist.";
};
return null;
}
[DllImport("Netapi32", CharSet = CharSet.Auto)]
static extern int NetApiBufferFree(IntPtr Buffer);
[DllImport("Netapi32", CharSet = CharSet.Auto)]
static extern int NetShareGetInfo([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string netname, int level, ref IntPtr bufptr);
/// <summary>
/// Retrieves the local path for the given server and share name.
/// </summary>
/// <remarks>serverName must start with \\</remarks>
static string NetShareGetPath(string serverName, string netName)
{
string path = null;
IntPtr ptr = IntPtr.Zero;
int errCode = NetShareGetInfo(serverName, netName, 2, ref ptr);
if (errCode == NERR_Success)
{
SHARE_INFO_2 shareInfo = (SHARE_INFO_2)Marshal.PtrToStructure(ptr, typeof(SHARE_INFO_2));
var members = from m in shareInfo.GetType().GetFields()
select m;
foreach (var m in members)
{
Console.WriteLine("{0}={1}", m.Name, m.GetValue(shareInfo));
}
path = shareInfo.shi2_path;
NetApiBufferFree(ptr);
}
else
Console.WriteLine(FormatMessage(errCode));
return path;
}
/// <summary>
/// The Main method is the entry point of the program, where the program control starts and
/// ends.
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
[STAThread]
static int Main(string[] args)
{
Console.WriteLine("path=" + NetShareGetPath(@"\\s3t21", "檔案測試區"));
Console.Read();
return 0;
}
const int ERROR_ACCESS_DENIED = 5;
const int ERROR_INVALID_LEVEL = 124; // unimplemented level for info
const int ERROR_INVALID_PARAMETER = 87;
const int ERROR_MORE_DATA = 234;
const int ERROR_NOT_ENOUGH_MEMORY = 8;
const int NERR_BufTooSmall = 2123; // The API return buffer is too small.
const int NERR_NetNameNotFound = 2310; // This shared resource does not exist.
const int NERR_Success = 0;
} // class MainConsole
http://pinvoke.net/default.aspx/netapi32.NetShareGetInfo