Question:
Can I save the file to a network directory using another user account?

Details:
There is a service running under the System account. The service, among other things, is engaged in synchronization with a third-party service from which you need to download files and add them to a network folder.
But System does not have access rights to the network folder.
But the service knows the username / password of the user who has such rights.

(So ​​far, only saving the file to temp and starting copying via Process.Start , but maybe there is something more elegant?)

    1 answer 1

    You can execute code inside your process from another user. First, import the WinAPI LogonUser function:

     [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool LogonUser( string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken); 

    And then like this:

     IntPtr token; if (LogonUser("SomeUser", "SomeDomain", "SomePwd", 2, 0, out token)) { var identity = new WindowsIdentity(token); using (identity.Impersonate()) { // здесь вы можете убедиться, что код выполняется под другим юзером Console.WriteLine(Environment.UserName); // делаем что-то File.WriteAllText(@"path.txt", "hello!"); } } else { Console.WriteLine("Invalid credentials"); }