gpt4 book ai didi

c# - 如何正确关闭与 WNetCancelConnection2 的连接?

转载 作者:可可西里 更新时间:2023-11-01 13:13:44 25 4
gpt4 key购买 nike

我想在需要时访问共享和取消访问。我使用以下代码:

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();
}
}

第一次 ListFiles() 调用成功。我预计第二次 ListFiles() 调用会失败,但它也会成功。如何正确取消连接?似乎 WNetCancelConnection2 不起作用。

这也说明here .我想知道是否有人可以让它发挥作用。

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
}

最佳答案

我遇到了类似的问题。我在代码中等待了 60 秒,然后网络连接才真正关闭。 Paulik 是对的,凭据缓存在某个地方,这使得我与其他凭据的下一次连接失败。但是,如果我使用 WNetCancelConnection2(pathname, flag, false) 关闭并等待 60 秒,我的新凭据将正常工作。不知道原因,但它确实有效。

关于c# - 如何正确关闭与 WNetCancelConnection2 的连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30887754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com