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

C# .NET桌面应用如何以当前用户身份访问网络文件夹?

解决C# .NET访问网络共享目录的权限问题

你当前用的WindowsIdentity.Impersonate()完全没用——你本来就在当前用户上下文里运行,模拟自己根本不会改变权限状态。下面是几个实际可行的解决办法:

1. 避免以管理员身份运行应用

如果你的应用是右键「以管理员身份运行」启动的,会切换到管理员上下文,这时候当前用户的网络凭据不会被带入这个独立上下文,导致访问网络共享失败。直接双击启动应用,用普通用户权限运行试试。

2. 手动添加网络凭据到Windows凭据管理器

有时候Windows没有自动缓存当前用户的网络凭据,你可以手动添加:

  • 打开控制面板→用户账户→凭据管理器→Windows凭据
  • 点击「添加Windows凭据」,输入网络共享的地址(比如\\fileserver\sharedfolder)、你的用户名(域用户要写域名\用户名)和密码,保存后再运行应用。

3. 用WNetAddConnection2 API显式建立网络连接

如果上面两种方法都不行,可以通过Windows API先显式建立到网络共享的连接,再用DirectoryInfo操作。以下是完整的C#代码实现:

首先定义API相关的结构体和方法:

using System;
using System.Runtime.InteropServices;

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

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

    [StructLayout(LayoutKind.Sequential)]
    private class NETRESOURCE
    {
        public int dwScope = 0;
        public int dwType = 1; // 指定为磁盘资源
        public int dwDisplayType = 0;
        public int dwUsage = 0;
        public string lpLocalName = "";
        public string lpRemoteName;
        public string lpComment = "";
        public string lpProvider = "";
    }

    // 建立网络连接
    public static void Connect(string networkPath, string username, string password)
    {
        NETRESOURCE nr = new NETRESOURCE();
        nr.lpRemoteName = networkPath;
        int result = WNetAddConnection2(ref nr, password, username, 0);
        if (result != 0)
        {
            throw new System.ComponentModel.Win32Exception(result);
        }
    }

    // 断开网络连接
    public static void Disconnect(string networkPath)
    {
        int result = WNetCancelConnection2(networkPath, 0, true);
        if (result != 0)
        {
            throw new System.ComponentModel.Win32Exception(result);
        }
    }
}

然后在你的业务代码里这样使用:

// 先建立连接再操作
try
{
    // 用当前用户凭据的话,username和password传null即可
    NetworkConnection.Connect(sourceFolder.Text, null, null);
    
    DirectoryInfo rootDir = new DirectoryInfo(sourceFolder.Text);
    // 执行你的文件遍历、读写等操作...
}
catch (Exception ex)
{
    // 按需处理异常,比如提示用户连接失败
}
finally
{
    // 可选:用完后断开连接,避免残留连接
    NetworkConnection.Disconnect(sourceFolder.Text);
}

这个方法会强制系统建立到目标共享的连接,确保DirectoryInfo等文件操作API能获取到正确的权限上下文。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 18:20:05