/// <summary>
/// 获取共享文件夹中指定文件
/// </summary>
/// <param name="server">IP地址</param>
/// <param name="userName">用户名</param>
/// <param name="pwd">密码</param>
/// <param name="shareDictoryName">共享文件夹名称</param>
/// <param name="fileName">指定文件名称</param>
/// <returns></returns>
public static string GetShareFile(string server, string userName, string pwd, string shareDictoryName, string fileName)
{
try
{
using (ShareToolHelper tool = new ShareToolHelper(userName, pwd, server))
{
string selectPath = $"\\\\{server}\\{shareDictoryName}";
var dicInfo = new DirectoryInfo(selectPath);//选择的目录信息
//DirectoryInfo[] dic = dicInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly);
//foreach (DirectoryInfo temp in dic)
//{
// Console.WriteLine(temp.FullName);
//}
var index = fileName.LastIndexOf(".");
var extendFileName = fileName.Substring(index, fileName.Length - index);
FileInfo[] textFiles = dicInfo.GetFiles($"*{extendFileName}", SearchOption.TopDirectoryOnly);//获取所有目录包含子目录下的文件
foreach (FileInfo temp in textFiles)
{
if (temp.Name == fileName)
{
return $"\\\\{server}\\{shareDictoryName}\\{temp.Name}";
}
}
return "";
}
}
catch (Exception ex)
{
throw;
}
}
public class ShareToolHelper : IDisposable
{
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
extern static bool CloseHandle(IntPtr handle);
[DllImport("Advapi32.DLL")]
static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
[DllImport("Advapi32.DLL")]
static extern bool RevertToSelf();
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_NEWCREDENTIALS = 9;//域控中的需要用:Interactive = 2
private bool disposed;
public ShareToolHelper(string username, string password, string ip)
{
// initialize tokens
IntPtr pExistingTokenHandle = new IntPtr(0);
IntPtr pDuplicateTokenHandle = new IntPtr(0);
try
{
// get handle to token
bool bImpersonated = LogonUser(username, ip, password,
LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
if (bImpersonated)
{
if (!ImpersonateLoggedOnUser(pExistingTokenHandle))
{
int nErrorCode = Marshal.GetLastWin32Error();
throw new Exception("ImpersonateLoggedOnUser error;Code=" + nErrorCode);
}
}
else
{
int nErrorCode = Marshal.GetLastWin32Error();
throw new Exception("LogonUser error;Code=" + nErrorCode);
}
}
finally
{
if (pExistingTokenHandle != IntPtr.Zero)
CloseHandle(pExistingTokenHandle);
if (pDuplicateTokenHandle != IntPtr.Zero)
CloseHandle(pDuplicateTokenHandle);
}
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
RevertToSelf();
disposed = true;
}
}
}