How to provide user name and password when connecting to a network share

后端 未结 11 1673
不知归路
不知归路 2020-11-22 00:34

When connecting to a network share for which the current user (in my case, a network enabled service user) has no rights, name and password have to be provided.

I kn

11条回答
  •  伪装坚强ぢ
    2020-11-22 01:02

    You can either change the thread identity, or P/Invoke WNetAddConnection2. I prefer the latter, as I sometimes need to maintain multiple credentials for different locations. I wrap it into an IDisposable and call WNetCancelConnection2 to remove the creds afterwards (avoiding the multiple usernames error):

    using (new NetworkConnection(@"\\server\read", readCredentials))
    using (new NetworkConnection(@"\\server2\write", writeCredentials)) {
       File.Copy(@"\\server\read\file", @"\\server2\write\file");
    }
    

提交回复
热议问题