nor*_*hov 7 c# windows winapi network-programming
我想在需要时访问共享并取消访问权限.我使用以下代码:
class Program
{
const string Share = "\\\\srv\\share";
static void ListFiles()
{
foreach (var dir in Directory.EnumerateDirectories(Share))
Console.WriteLine(dir);
}
static void Main(string[] args)
{
using (var connection = new NetworkConnection(Share, new System.Net.NetworkCredential("user", "password")))
ListFiles();
ListFiles();
}
}
Run Code Online (Sandbox Code Playgroud)
第一个ListFiles()调用成功.我希望第二次ListFiles()调用失败但它也会成功.如何正确取消连接?似乎WNetCancelConnection2不起作用.
这也在这里说明.我想知道是否有人能让它发挥作用.
FIY这是一个网络连接类:
public class NetworkConnection : IDisposable
{
string _networkName;
public NetworkConnection(string networkName,
NetworkCredential credentials)
{
_networkName = networkName;
var netResource = new NetResource()
{
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplaytype.Share,
RemoteName = networkName
};
var userName = string.IsNullOrEmpty(credentials.Domain)
? credentials.UserName
: string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);
var result = WNetAddConnection2(
netResource,
credentials.Password,
userName,
0);
if (result != 0)
{
throw new Win32Exception(result, "Error connecting to remote share");
}
}
~NetworkConnection()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
WNetCancelConnection2(_networkName, 0, true);
}
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2(NetResource netResource,
string password, string username, int flags);
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2(string name, int flags,
bool force);
}
[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
public ResourceScope Scope;
public ResourceType ResourceType;
public ResourceDisplaytype DisplayType;
public int Usage;
public string LocalName;
public string RemoteName;
public string Comment;
public string Provider;
}
public enum ResourceScope : int
{
Connected = 1,
GlobalNetwork,
Remembered,
Recent,
Context
};
public enum ResourceType : int
{
Any = 0,
Disk = 1,
Print = 2,
Reserved = 8,
}
public enum ResourceDisplaytype : int
{
Generic = 0x0,
Domain = 0x01,
Server = 0x02,
Share = 0x03,
File = 0x04,
Group = 0x05,
Network = 0x06,
Root = 0x07,
Shareadmin = 0x08,
Directory = 0x09,
Tree = 0x0a,
Ndscontainer = 0x0b
}
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的问题,不幸的是,没有找到合适的解决方案。我只能描述一下我的研究结果。
此方法在底层使用“net use /delete”命令。它工作正常并删除网络连接。您可以通过在命令窗口中调用“ net use ”来检查。连接已关闭,但是凭据仍缓存在某处。
所以这个问题的主要原因是缓存的凭据。您可以尝试在“运行”窗口中调用“control keymgr.dll”的凭据管理器中找到它们,但在我的情况下,它们没有显示。凭据可能被 explorer.exe 缓存,因此您可以尝试打开任务管理器并重新启动它。
摆脱它们的唯一可靠方法是 使用“net stop”“net start”命令重新启动工作站服务。
| 归档时间: |
|
| 查看次数: |
2651 次 |
| 最近记录: |