File.Create Network Share不同的凭据覆盖

时间:2015-11-19 14:36:12

标签: c# credentials network-shares

我正在使用C#编写一个Windows应用程序。我有一个要求,即上传到Windows窗体的文件将保存到网络共享中,但并非所有用户都可以访问网络共享( \\ FileServer \ SharedFolder )。只有一个用户( FileWriter )具有此文件夹的读/写/执行权限。当前用户 EmployeeUser 对此共享没有任何权限。我已通过打开开始 - >运行 \\ FileServer \ SharedFolder 验证了这一点。这会出现“拒绝访问”错误框。

我使用this example from SO Post,使用<xsl:template match="text()"/> 连接 FileWriter 的不同凭据,以使用 Sample.txt > File.Create 即可。到目前为止一切正常。WNetAddConnection2被调用,我已在代码调试中验证,并退出程序。现在来自当前用户,我已经打开了 StartMenu - &gt;运行并键入 \\ FileServer \ SharedFolder ,即使Windows用户为 EmployeeUser ,也会立即打开共享。我关闭了资源管理器,几分钟后(通过尝试随机更改)我打开了开始 - &gt;运行 \\ FileServer \ SharedFolder 。现在它提供了一个Access Denied错误框。

我无法理解这一点,非常感谢您对此的任何帮助。

现在,在Access Denied框之后,我以相同的步骤再次运行程序,只是 Sample.txt (使用File.Create)被静默覆盖。是不是应该给出文件存在错误?

1 个答案:

答案 0 :(得分:0)

您可以改为使用模仿:

using (var impersonator = new Impersonator(username, password))
{
    File.Copy(source, destination, true);
}

这是我们实施的副本,因此请调整您的域名

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;

public class Impersonator : IDisposable
{
/// <summary>
///     The Impersonator class is used to access a network share with other credentials.
/// </summary>
private readonly WindowsImpersonationContext _impersonatedUser;

private readonly IntPtr _userHandle;

/// <summary>
///     Constructor
/// </summary>
/// <param name="username">The user of the network share</param>
/// <param name="password">The password of the network share</param>
public Impersonator(string username, string password, string userDomain =   "YOURDOMAIN")
{
    _userHandle = new IntPtr(0);
    bool returnValue = LogonUser(username, userDomain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                                 ref _userHandle);
    if (!returnValue)
        throw new ApplicationException(
            "The applications wasn't able to impersonate the user with the specified credentials!");
    var newId = new WindowsIdentity(_userHandle);
    _impersonatedUser = newId.Impersonate();
}

#region IDisposable Members

public void Dispose()
{
    if (_impersonatedUser != null)
    {
        _impersonatedUser.Undo();
        CloseHandle(_userHandle);
    }
}

#endregion

#region Interop imports/constants

public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_LOGON_SERVICE = 3;
public const int LOGON32_PROVIDER_DEFAULT = 0;

[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern bool LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType,
                                    int dwLogonProvider, ref IntPtr phToken);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

#endregion
}