C#如何访问共享文件夹或者磁盘
本文实例为大家分享了C#访问共享文件夹或者磁盘的具体代码,供大家参考,具体内容如下
SharedTool:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Runtime.InteropServices;
namespaceConsoleApplication5
{
publicclassSharedTool:IDisposable
{
//obtainsusertoken
[DllImport("advapi32.dll",SetLastError=true)]
staticexternboolLogonUser(stringpszUsername,stringpszDomain,stringpszPassword,
intdwLogonType,intdwLogonProvider,refIntPtrphToken);
//closesopenhandesreturnedbyLogonUser
[DllImport("kernel32.dll",CharSet=CharSet.Auto)]
externstaticboolCloseHandle(IntPtrhandle);
[DllImport("Advapi32.DLL")]
staticexternboolImpersonateLoggedOnUser(IntPtrhToken);
[DllImport("Advapi32.DLL")]
staticexternboolRevertToSelf();
constintLOGON32_PROVIDER_DEFAULT=0;
constintLOGON32_LOGON_NEWCREDENTIALS=9;//域控中的需要用:Interactive=2
privatebooldisposed;
publicSharedTool(stringusername,stringpassword,stringip)
{
//initializetokens
IntPtrpExistingTokenHandle=newIntPtr(0);
IntPtrpDuplicateTokenHandle=newIntPtr(0);
try
{
//gethandletotoken
boolbImpersonated=LogonUser(username,ip,password,
LOGON32_LOGON_NEWCREDENTIALS,LOGON32_PROVIDER_DEFAULT,refpExistingTokenHandle);
if(bImpersonated)
{
if(!ImpersonateLoggedOnUser(pExistingTokenHandle))
{
intnErrorCode=Marshal.GetLastWin32Error();
thrownewException("ImpersonateLoggedOnUsererror;Code="+nErrorCode);
}
}
else
{
intnErrorCode=Marshal.GetLastWin32Error();
thrownewException("LogonUsererror;Code="+nErrorCode);
}
}
finally
{
//closehandle(s)
if(pExistingTokenHandle!=IntPtr.Zero)
CloseHandle(pExistingTokenHandle);
if(pDuplicateTokenHandle!=IntPtr.Zero)
CloseHandle(pDuplicateTokenHandle);
}
}
protectedvirtualvoidDispose(booldisposing)
{
if(!disposed)
{
RevertToSelf();
disposed=true;
}
}
publicvoidDispose()
{
Dispose(true);
}
}
}
案例:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.IO;
namespaceConsoleApplication5
{
classProgram
{
staticvoidMain(string[]args)
{
using(SharedTooltool=newSharedTool("administrator","12345678","192.168.1.101"))
{
stringselectPath=@"\\192.168.1.101\c$";
vardicInfo=newDirectoryInfo(selectPath);//选择的目录信息
DirectoryInfo[]dic=dicInfo.GetDirectories("*.*",SearchOption.TopDirectoryOnly);
foreach(DirectoryInfotempindic)
{
Console.WriteLine(temp.FullName);
}
Console.WriteLine("---------------------------");
FileInfo[]textFiles=dicInfo.GetFiles("*.*",SearchOption.TopDirectoryOnly);//获取所有目录包含子目录下的文件
foreach(FileInfotempintextFiles)
{
Console.WriteLine(temp.Name);
}
}
Console.ReadKey();
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。