|
How to check if a given share exist on a server?
This article and sample code demonstrates how you can use Win32 NetApi
functions through PInvoke/Interop to check if a given share resource
exists on a server or not. The standard Win32 call to check this is NetCheckShare.
We will define prototype for this function in our C# class and then call
wherever it is necessary.
using System;
using System.Runtime.InteropServices;
namespace PardesiServices.NetInterop
{
public class NetApiWin32
{
[DllImport("Netapi32.dll")]
public static extern int NetShareCheck(
[MarshalAs(UnmanagedType.LPWStr)]string ServerName,
[MarshalAs(UnmanagedType.LPWStr)]string Device,
out long Type);
}
}
And then this protoype function can be called in the application as shown below.
bool IsResourceShared(string strServer, string strResourceName, out ShareType nType)
{
bool bRet = false;
nType = ShareType.STYPE_DISKTREE;
long lType = 0;
int nRet = NetApiWin32.NetShareCheck(strServer, strResourceName, out lType);
bRet = (0 == nRet);
if (!bRet)
{
if (nRet == 2311)
{
Console.WriteLine("Device not shared");
}
else if (nRet == 2310)
{
Console.WriteLine("The device does not exist");
}
else
{
Console.WriteLine("Unknown win32 error");
}
}
else
{
nType = (ShareType)lType;
}
return bRet;
}
|