如何在代码中添加远程服务器凭据,无需映射网络驱动器保存图片至UNC路径
在C#中直接通过代码携带凭据保存图片到UNC路径
我之前也碰到过一模一样的需求——不用手动映射网络驱动器输入凭据,直接在代码里搞定UNC共享的访问权限,然后保存图片。下面给你一套可落地的方案,核心是调用Windows的Win32网络API来添加临时凭据连接:
步骤1:引入Win32网络连接API
首先我们需要在代码里引入Windows原生的WNetAddConnection2和WNetCancelConnection2函数,用来建立和断开带凭据的网络连接。在你的类里添加以下代码:
using System.Runtime.InteropServices; using System.IO; // 定义网络连接所需的结构体 [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; } // 引入Win32 API [DllImport("mpr.dll", CharSet = CharSet.Unicode)] private static extern int WNetAddConnection2(ref NETRESOURCE lpNetResource, string lpPassword, string lpUsername, int dwFlags); [DllImport("mpr.dll", CharSet = CharSet.Unicode)] private static extern int WNetCancelConnection2(string lpName, int dwFlags, bool fForce);
步骤2:封装建立网络连接的方法
写一个简单的静态方法,用来传入UNC共享路径、用户名和密码,建立临时连接:
private static bool ConnectToUncShare(string uncPath, string username, string password) { NETRESOURCE nr = new NETRESOURCE(); nr.dwType = 0x00000001; // 资源类型为磁盘 nr.lpRemoteName = uncPath; // 调用API建立连接,0表示成功 int result = WNetAddConnection2(ref nr, password, username, 0); return result == 0; } // 可选:封装断开连接的方法 private static bool DisconnectFromUncShare(string uncPath) { int result = WNetCancelConnection2(uncPath, 0, true); return result == 0; }
步骤3:修改你的图片保存方法
现在把你的OnPostTransfer方法修改一下,先建立带凭据的连接,再保存图片,最后按需断开连接:
public bool OnPostTransfer(Bitmap bit) { m_ImageCore.IO.LoadImage(bit); string fil_name = "new_f.jpg"; // 注意:这里只需要到共享目录的UNC路径,不要包含文件名 string uncSharePath = @"\\WIN-KCA4SC9E2U4\Users\hosam\embs"; string fullSavePath = Path.Combine(uncSharePath, fil_name); string username = "你的共享服务器用户名"; // 格式可以是 "DOMAIN\用户名" 或 "机器名\用户名" string password = "你的共享服务器密码"; bool connectionSuccess = false; try { // 先建立带凭据的网络连接 connectionSuccess = ConnectToUncShare(uncSharePath, username, password); if (!connectionSuccess) { // 处理连接失败的情况,比如日志记录或返回错误 return false; } // 执行图片保存操作(如果你的m_ImageCore有专属保存方法,替换成你原来的逻辑即可) bit.Save(fullSavePath, System.Drawing.Imaging.ImageFormat.Jpeg); return true; } catch (Exception ex) { // 处理保存过程中的异常,比如IO异常、权限问题等 Console.WriteLine($"保存图片失败:{ex.Message}"); return false; } finally { // 不管成功失败,都断开连接(如果需要长期保持连接可以去掉这一步) if (connectionSuccess) { DisconnectFromUncShare(uncSharePath); } } }
注意事项
- 用户名格式:如果是域环境下的共享,用户名要写成
域名称\用户名;如果是工作组机器的本地用户,写成机器名称\用户名。 - 权限问题:确保你提供的用户账号对目标UNC目录有写入权限,否则会保存失败。
- 异常处理:记得在实际项目中添加更完善的日志和异常捕获,方便排查问题。
内容的提问来源于stack exchange,提问作者user2940558
相关产品推荐
相关产品推荐

