gpt4 book ai didi

c# - 如何在 C# 中使用身份验证打开文件夹?

转载 作者:行者123 更新时间:2023-11-30 17:28:34 25 4
gpt4 key购买 nike

enter image description here如何在 C# 中使用身份验证打开文件夹?我已经使用了 LogonUser 但它不起作用...

IntPtr token = IntPtr.Zero;
bool success = LogonUser("username", "domainname", "password",
2, 0, ref token);
if (success)
{
using (WindowsImpersonationContext person = new WindowsIdentity(token).Impersonate())
{
File.Copy(sourceFileName,destFileName);

person.Undo();
CloseHandle(token);
}
}

成功是真的,我在 token 中收到一个数字,它输入 if 并给出用户错误和密码。

Everything works fine until it reaches the File.Copy part ERROR: I still got this error "Additional information: Logon failure: unknown user name or bad password."

最佳答案

我更改了代码,它对我来说工作正常,我把它留在这里以备不时之需。


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI.WebControls;

namespace BBVA.Canales.Front.Net.UI.WebApp.Servicios.ViewModels
{
public class NetworkShare
{
[DllImport("Mpr.dll")]
private static extern int WNetUseConnection(
IntPtr hwndOwner,
NETRESOURCE lpNetResource,
string lpPassword,
string lpUserID,
int dwFlags,
string lpAccessName,
string lpBufferSize,
string lpResult
);

[DllImport("Mpr.dll")]
private static extern int WNetCancelConnection(
string lpName,
bool fForce
);

[StructLayout(LayoutKind.Sequential)]
private class NETRESOURCE
{
public int dwScope = 0;
public int dwType = 0;
public int dwDisplayType = 0;
public int dwUsage = 0;
public string lpLocalName = "";
public string lpRemoteName = "";
public string lpComment = "";
public string lpProvider = "";
}

const int RESOURCETYPE_DISK = 0x00000001;
const int CONNECT_UPDATE_PROFILE = 0x00000001;


public static void ConnectToShare(string uri, string username, string password, string idFile, HttpPostedFileBase file)
{
//Create netresource and point it at the share
NETRESOURCE nr = new NETRESOURCE();
nr.dwType = RESOURCETYPE_DISK;
nr.lpRemoteName = uri;

//Create the share
int ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);

file.SaveAs(@"\\c:\Desktop\FolderName\" + idFile);

}

public static void DisconnectFromShare(string uri, bool force)
{
//remove the share
int ret = WNetCancelConnection(uri, force);

}



}
}

然后从您的代码中调用它:

 ConnectToShare("dom", @"user", @"psw", file);
DisconnectFromShare("dom", false);

关于c# - 如何在 C# 中使用身份验证打开文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52657325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com