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

Windows Server 2016下C#创建共享文件夹提示用户名密码错误求助

解决C#访问Windows共享文件夹时的"用户名或密码错误"问题

方案1:修正CredentialCache的认证类型与Uri

  • 核心问题:你代码中使用的Basic认证并非Windows SMB共享的默认协议,Windows共享优先使用NTLM或Negotiate;同时CredentialCache绑定的Uri指向服务器根目录,而非具体共享文件夹,导致凭据无法匹配请求。
  • 修改后的代码:
NetworkCredential theNetworkCredential = new NetworkCredential("username", "password");
CredentialCache theNetcache = new CredentialCache();
// 将认证类型改为NTLM,Uri指向具体共享文件夹路径
theNetcache.Add(new Uri(@"\\WIN-FM8PGNEC4OF\Archives"), "NTLM", theNetworkCredential);
string subdir = @"\\WIN-FM8PGNEC4OF\Archives\BN\" + entity + @"\" + folder;
if (!Directory.Exists(subdir))
{
    try
    {
        Directory.CreateDirectory(subdir);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return;
    }
}

方案2:调用Windows API手动建立共享连接

如果方案1仍无效,可直接调用Windows系统API预先建立共享连接,确保凭据被正确加载:

  • 先定义API调用所需的结构体和方法:
using System.Runtime.InteropServices;

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

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

    public static void ConnectToSharedFolder(string remotePath, string username, string password)
    {
        NETRESOURCE nr = new NETRESOURCE();
        nr.dwType = 0x00000001; // 指定为磁盘类型共享
        nr.lpRemoteName = remotePath;

        int result = WNetAddConnection2(ref nr, password, username, 0);
        if (result != 0)
        {
            throw new System.ComponentModel.Win32Exception(result);
        }
    }
}
  • 在创建文件夹前调用该方法:
try
{
    // 先建立共享连接
    NetworkConnection.ConnectToSharedFolder(@"\\WIN-FM8PGNEC4OF\Archives", "username", "password");
    string subdir = @"\\WIN-FM8PGNEC4OF\Archives\BN\" + entity + @"\" + folder;
    if (!Directory.Exists(subdir))
    {
        Directory.CreateDirectory(subdir);
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
    return;
}

问题原因说明

手动通过Win+R访问共享后程序能正常运行,是因为Windows会自动缓存你输入的凭据,后续程序访问共享时会直接使用该缓存凭据。而原始代码因认证类型不匹配、Uri指向错误,导致凭据未被正确传递到共享访问请求,从而抛出"用户名或密码错误"异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:39:17