如何通过代码自动登录Windows网络共享文件夹实现文件操作?
如何自动完成Windows网络共享的登录操作
场景说明
Windows网络共享文件夹可直接通过代码像本地文件一样操作,例如用C++标准库实现文件复制与写入:
#include <filesystem> using namespace std; namespace fs = std::filesystem; int main(int argc, wchar_t* argv[]) { fs::path fromPath = L"D:\\temp\\test.zip"; fs::path toPath = LR"(\\127.0.0.1\ProgramData\test.zip)"; std::error_code ec; bool b = fs::copy_file(fromPath, toPath, ec); cout << (b ? "OK" : ec.message()) << endl; std::ofstream fout(LR"(\\127.0.0.1\ProgramData\test.txt)"); fout << "abc"; }
但执行这类代码前,通常需要手动完成目标机器的网络登录(输入共享账号密码的验证步骤),接下来介绍如何通过代码自动完成该登录流程。
自动登录的实现方案
可以使用Windows系统API中的WNetAddConnection2函数,直接在代码中传入共享路径、账号和密码,完成自动认证。
完整示例代码
#include <windows.h> #include <iostream> #include <filesystem> using namespace std; namespace fs = std::filesystem; // 封装网络共享登录函数 bool ConnectNetworkShare(const wchar_t* sharePath, const wchar_t* username, const wchar_t* password) { NETRESOURCEW nr = {0}; nr.dwType = RESOURCETYPE_DISK; // 指定共享类型为磁盘 nr.lpRemoteName = (LPWSTR)sharePath; DWORD ret = WNetAddConnection2W(&nr, password, username, 0); if (ret == NO_ERROR) { cout << "共享登录成功" << endl; return true; } else { // 将错误码转为可读信息 wchar_t errMsg[256]; FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, ret, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), errMsg, sizeof(errMsg)/sizeof(wchar_t), nullptr); wcout << L"登录失败:" << errMsg << endl; return false; } } int main(int argc, wchar_t* argv[]) { // 配置共享信息 const wchar_t* targetShare = LR"(\\127.0.0.1\ProgramData)"; const wchar_t* shareUser = L"目标机器的共享账号"; const wchar_t* sharePwd = L"对应账号的密码"; // 先完成自动登录 if (!ConnectNetworkShare(targetShare, shareUser, sharePwd)) { return 1; } // 执行文件操作 fs::path fromPath = L"D:\\temp\\test.zip"; fs::path toPath = LR"(\\127.0.0.1\ProgramData\test.zip)"; std::error_code ec; bool copyResult = fs::copy_file(fromPath, toPath, ec); cout << (copyResult ? "文件复制成功" : ec.message()) << endl; std::ofstream fout(LR"(\\127.0.0.1\ProgramData\test.txt)"); if (fout.is_open()) { fout << "abc"; cout << "文件写入成功" << endl; fout.close(); } else { cout << "文件写入失败" << endl; } // 可选:操作完成后断开共享连接 DWORD cancelRet = WNetCancelConnection2W(targetShare, 0, TRUE); if (cancelRet == NO_ERROR) { cout << "共享连接已断开" << endl; } return 0; }
关键注意点
- 权限验证:确保传入的账号已被授予目标共享文件夹的对应操作权限(读/写)
- 域环境适配:若当前机器与目标机器在同一域中,可省略账号密码参数,直接使用当前登录凭据登录
- 错误处理:示例中加入了
FormatMessage函数,可将API返回的错误码转为可读提示,便于调试 - 连接清理:使用
WNetCancelConnection2可在操作完成后断开共享连接,避免系统残留无效连接
内容的提问来源于stack exchange,提问作者Zhang
相关产品推荐
相关产品推荐

