在此之前有项目中遇到需要操作共享目录里面的文件,因此记录一下:
下面的核心代码是用来在共享目录下载文件时使用:
/// <summary>
/// 身份标识 2019年4月10日01:11:15 Dennyhui
/// </summary>
public class IdentityScope : IDisposable
{
// obtains user token
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
// closes open handes returned by LogonUser
[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;//域?控?中D的?需è要癮用?:Interactive = 2
private bool disposed;
/// <summary>
/// 创建身份标识 2019年4月10日01:11:35 Dennyhui
/// </summary>
/// <param name="sUsername">用户名</param>
/// <param name="sDomain">域名</param>
/// <param name="sPassword">密码</param>
public IdentityScope(string sUsername, string sDomain, string sPassword)
{
// initialize tokens
IntPtr pExistingTokenHandle = new IntPtr(0);
IntPtr pDuplicateTokenHandle = new IntPtr(0);
try
{
// get handle to token
bool bImpersonated = LogonUser(sUsername, sDomain, sPassword,
LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
if (true == 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
{
// close handle(s)
if (pExistingTokenHandle != IntPtr.Zero)
CloseHandle(pExistingTokenHandle);
if (pDuplicateTokenHandle != IntPtr.Zero)
CloseHandle(pDuplicateTokenHandle);
}
}
下载文件:
using (IdentityScope iss = new IdentityScope(user, sftpIP, pwd))
{
DirectoryInfo Dir = new DirectoryInfo(sftpInPath);
//找到该目录下的文件
FileInfo[] fis = Dir.GetFiles();
//do something....
});
上传文件:
/// <summary>
/// 上传文件到共享目录 2019年4月7日17:21:13 Dennyhui
/// </summary>
/// <param name="fileNamePath">文件路径</param>
/// <param name="urlPath">共享路径</param>
/// <param name="User">用户名</param>
/// <param name="Pwd">密码</param>
public static void UpLoadFile(string fileNamePath, string urlPath, string User, string Pwd)
{
try
{
string newFileName = fileNamePath.Substring(fileNamePath.LastIndexOf(@"\") + 1);//取文件名称
Log.CreateLogManager().Error(newFileName);
if (urlPath.EndsWith(@"\") == false) urlPath = urlPath + @"\";
urlPath = urlPath + newFileName;
WebClient myWebClient = new WebClient();
NetworkCredential cread = new NetworkCredential(User, Pwd, "Domain");
myWebClient.Credentials = cread;
using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
{
BinaryReader r = new BinaryReader(fs);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(urlPath);
// postStream.m
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
}
else
{
Log.CreateLogManager().Error("文件上传错误!");
}
postStream.Close();
fs.Close();
fs.Dispose();
}
}
catch (Exception ex)
{
Log.CreateLogManager().Error("文件上传发生错误:" + ex);
}
}
更多文章请扫码关注公众号,有问题的小伙伴也可以在公众号上提出。