You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Winform断开UNC映射文件夹后如何禁止资源管理器访问该路径

解决方案

方法1:补充命令清理残留缓存(适配当前net use实现方案)

你当前仅删除了UNC映射条目,没有清理Windows留存的SMB凭证和会话缓存,补充执行2条命令即可解决残留问题:

  • 第一步:删除Windows凭证管理器中存储的对应共享凭证
    cmdkey /delete:\\1.1.1.1
  • 第二步:强制断开本地与目标IP的SMB会话
    若有管理员权限,执行:
    net session \\1.1.1.1 /delete /y
    若为普通用户权限,执行:
    net use \\1.1.1.1\ipc$ /delete /y

注意:执行清理命令时,确保当前系统没有其他进程正在访问该SMB共享,否则会触发自动重连,导致缓存重新生成。

方法2:改用Windows原生API操作(更可控,推荐C#项目使用)

直接调用WNetAddConnection2、WNetCancelConnection2API比调用外部net use命令稳定性更高,还可以直接指定临时连接属性,从根源禁止凭证缓存:

定义API导入和封装方法

using System;
using System.Runtime.InteropServices;

public class SMBConnectionTool
{
    [StructLayout(LayoutKind.Sequential)]
    private class NETRESOURCE
    {
        public int dwScope = 0;
        public int dwType = 0;
        public int dwDisplayType = 0;
        public int dwUsage = 0;
        public string lpLocalName = null;
        public string lpRemoteName = null;
        public string lpComment = null;
        public string lpProvider = null;
    }

    [DllImport("mpr.dll")]
    private static extern int WNetAddConnection2(NETRESOURCE lpNetResource, string lpPassword, string lpUserName, int dwFlags);

    [DllImport("mpr.dll")]
    private static extern int WNetCancelConnection2(string lpName, int dwFlags, bool fForce);

    private const int RESOURCETYPE_DISK = 0x1;
    private const int CONNECT_TEMPORARY = 0x00000004; // 关键标识:标记为临时连接,不缓存凭证

    /// <summary>
    /// 建立SMB共享连接
    /// </summary>
    public static int Connect(string remoteSharePath, string userName, string password)
    {
        NETRESOURCE nr = new NETRESOURCE();
        nr.dwType = RESOURCETYPE_DISK;
        nr.lpRemoteName = remoteSharePath;
        return WNetAddConnection2(nr, password, userName, CONNECT_TEMPORARY);
    }

    /// <summary>
    /// 断开SMB共享连接
    /// </summary>
    public static int Disconnect(string remoteSharePath, bool forceDisconnect = true)
    {
        return WNetCancelConnection2(remoteSharePath, 0, forceDisconnect);
    }
}

调用示例

// 建立连接
int result = SMBConnectionTool.Connect(@"\\1.1.1.1\folder", @"1.1.1.1\Username", "yourPassword");
if(result == 0)
{
    // 连接成功,执行文件读写逻辑
    // ...

    // 操作完成后断开连接
    SMBConnectionTool.Disconnect(@"\\1.1.1.1\folder");
    // 补充清理凭证缓存,双重保险
    System.Diagnostics.Process.Start("cmd.exe", "/c cmdkey /delete:\\\\1.1.1.1").WaitForExit();
}

额外注意事项

  • 不要在程序运行期间手动通过资源管理器访问该SMB共享路径,资源管理器会自动持有SMB会话并触发自动重连,导致清理失效
  • 如果程序运行在服务上下文,建议将服务配置为独立用户运行,和本地登录用户的会话隔离,避免会话共享导致的凭证泄露
  • 涉及密码存储的场景,建议将密码加密后保存在配置文件中,不要硬编码在程序代码里

内容的提问来源于stack exchange,提问作者Andie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:45:10