将文件复制到网络共享驱动器上

发布于 2024-08-05 02:13:33 字数 104 浏览 14 评论 0原文

我有一个网络共享驱动器(“\serveur\folder”),我想在其中复制文件。 我可以使用特定用户(“用户”/“通行证”)在驱动器上写入内容。 如何使用 C# 访问具有写入权限的共享驱动器?

I have a network shared drive ("\serveur\folder") on which I would like to copy file.
I can write on the drive with a specific user ("user"/"pass").
How can I access the shared drived with write privilege using C#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

半葬歌 2024-08-12 02:13:33

未经测试的代码,但它将类似于:

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

// http://pinvoke.net/default.aspx/advapi32/LogonUser.html    
IntPtr token;
LogonUser("username", "domain", "password", LogonType.LOGON32_LOGON_BATCH, LogonProvider.LOGON32_PROVIDER_DEFAULT);

WindowsIdentity identity = new WindowsIdentity(token);

WindowsImpersonationContext context = identity.Impersonate();

try
{
    File.Copy(@"c:\temp\MyFile.txt", @"\\server\folder\Myfile.txt", true);
}
finally
{
    context.Undo();
}

Untested code, but it will be similiar to:

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

// http://pinvoke.net/default.aspx/advapi32/LogonUser.html    
IntPtr token;
LogonUser("username", "domain", "password", LogonType.LOGON32_LOGON_BATCH, LogonProvider.LOGON32_PROVIDER_DEFAULT);

WindowsIdentity identity = new WindowsIdentity(token);

WindowsImpersonationContext context = identity.Impersonate();

try
{
    File.Copy(@"c:\temp\MyFile.txt", @"\\server\folder\Myfile.txt", true);
}
finally
{
    context.Undo();
}
╰◇生如夏花灿烂 2024-08-12 02:13:33

下面是 ASP.NET 应用程序的工作示例。 原始来源

private void SendToFileShare(byte[] pdfData, string fileName)
{
    if(pdfData == null)
    {
        throw new ArgumentNullException("pdfData");
    }
    if (string.IsNullOrWhiteSpace(fileName))
    {
        //Assign a unique name because the programmer failed to specify one.
        fileName = Guid.NewGuid().ToString();
    }
    else
    {
        //Should probably replace special characters (windows filenames) with something.                
    }


    string networkShareLocation = @"\\your\network\share\";

    var path = $"{networkShareLocation}{fileName}.pdf";


    //Credentials for the account that has write-access. Probably best to store these in a web.config file.
    var domain = "AB";
    var userID = "Mr";
    var password = "C";


    if (ImpersonateUser(domain, userID, password) == true)
    {
        //write the PDF to the share:
        System.IO.File.WriteAllBytes(path, report);

        undoImpersonation();
    }
    else
    {
        //Could not authenticate account. Something is up.
        //Log or something.
    }
}

/// <summary>
/// Impersonates the given user during the session.
/// </summary>
/// <param name="domain">The domain.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password.</param>
/// <returns></returns>
private bool ImpersonateUser(string domain, string userName, string password)
{
    WindowsIdentity tempWindowsIdentity;
    IntPtr token = IntPtr.Zero;
    IntPtr tokenDuplicate = IntPtr.Zero;

    if (RevertToSelf())
    {
        if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
            LOGON32_PROVIDER_DEFAULT, ref token) != 0)
        {
            if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
            {
                tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                impersonationContext = tempWindowsIdentity.Impersonate();
                if (impersonationContext != null)
                {
                    CloseHandle(token);
                    CloseHandle(tokenDuplicate);
                    return true;
                }
            }
        }
    }
    if (token != IntPtr.Zero)
        CloseHandle(token);
    if (tokenDuplicate != IntPtr.Zero)
        CloseHandle(tokenDuplicate);
    return false;
}

/// <summary>
/// Undoes the current impersonation.
/// </summary>
private void undoImpersonation()
{
    impersonationContext.Undo();
}


#region Impersionation global variables
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

WindowsImpersonationContext impersonationContext;

[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
    String lpszDomain,
    String lpszPassword,
    int dwLogonType,
    int dwLogonProvider,
    ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
    int impersonationLevel,
    ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();

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

Here's a working example for ASP.NET applications. Original source

private void SendToFileShare(byte[] pdfData, string fileName)
{
    if(pdfData == null)
    {
        throw new ArgumentNullException("pdfData");
    }
    if (string.IsNullOrWhiteSpace(fileName))
    {
        //Assign a unique name because the programmer failed to specify one.
        fileName = Guid.NewGuid().ToString();
    }
    else
    {
        //Should probably replace special characters (windows filenames) with something.                
    }


    string networkShareLocation = @"\\your\network\share\";

    var path = $"{networkShareLocation}{fileName}.pdf";


    //Credentials for the account that has write-access. Probably best to store these in a web.config file.
    var domain = "AB";
    var userID = "Mr";
    var password = "C";


    if (ImpersonateUser(domain, userID, password) == true)
    {
        //write the PDF to the share:
        System.IO.File.WriteAllBytes(path, report);

        undoImpersonation();
    }
    else
    {
        //Could not authenticate account. Something is up.
        //Log or something.
    }
}

/// <summary>
/// Impersonates the given user during the session.
/// </summary>
/// <param name="domain">The domain.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password.</param>
/// <returns></returns>
private bool ImpersonateUser(string domain, string userName, string password)
{
    WindowsIdentity tempWindowsIdentity;
    IntPtr token = IntPtr.Zero;
    IntPtr tokenDuplicate = IntPtr.Zero;

    if (RevertToSelf())
    {
        if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
            LOGON32_PROVIDER_DEFAULT, ref token) != 0)
        {
            if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
            {
                tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                impersonationContext = tempWindowsIdentity.Impersonate();
                if (impersonationContext != null)
                {
                    CloseHandle(token);
                    CloseHandle(tokenDuplicate);
                    return true;
                }
            }
        }
    }
    if (token != IntPtr.Zero)
        CloseHandle(token);
    if (tokenDuplicate != IntPtr.Zero)
        CloseHandle(tokenDuplicate);
    return false;
}

/// <summary>
/// Undoes the current impersonation.
/// </summary>
private void undoImpersonation()
{
    impersonationContext.Undo();
}


#region Impersionation global variables
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

WindowsImpersonationContext impersonationContext;

[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
    String lpszDomain,
    String lpszPassword,
    int dwLogonType,
    int dwLogonProvider,
    ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
    int impersonationLevel,
    ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
#endregion
静若繁花 2024-08-12 02:13:33

更简单和现代的方法。在企业网络中为我工作。

 try
{
    bool validLogin = false;
    using (PrincipalContext tempcontext = new PrincipalContext(ContextType.Domain, "domain.company.com", null, ContextOptions.Negotiate))
    {
        try
        {
            validLogin = tempcontext.ValidateCredentials("USERNAME", "PASSWORD", ContextOptions.Negotiate);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    if (validLogin)
    {
        File.Copy(@"C:\folder\filename.txt", @"\\domain\folder\filename.txt", true);
        return true;
    }
    else
    {
        MessageBox.Show("Username or Password is incorrect...", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return false;
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
    return false;
}

More simple and modern approach. Works for me in an enterprise network.

 try
{
    bool validLogin = false;
    using (PrincipalContext tempcontext = new PrincipalContext(ContextType.Domain, "domain.company.com", null, ContextOptions.Negotiate))
    {
        try
        {
            validLogin = tempcontext.ValidateCredentials("USERNAME", "PASSWORD", ContextOptions.Negotiate);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    if (validLogin)
    {
        File.Copy(@"C:\folder\filename.txt", @"\\domain\folder\filename.txt", true);
        return true;
    }
    else
    {
        MessageBox.Show("Username or Password is incorrect...", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return false;
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
    return false;
}
三生路 2024-08-12 02:13:33

创建一个具有写入网络驱动器权限的用户,并在 C# 中使用模拟来在访问该驱动器时使用该用户。

Create a user with privileges to write to the network drive and use impersonation within the c# to use that user when accessing the drive.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文