C#如何访问共享文件夹或者磁盘
程序员文章站
2023-12-15 08:52:04
本文实例为大家分享了c#访问共享文件夹或者磁盘的具体代码,供大家参考,具体内容如下
sharedtool:
using system;
using s...
本文实例为大家分享了c#访问共享文件夹或者磁盘的具体代码,供大家参考,具体内容如下
sharedtool:
using system; using system.collections.generic; using system.linq; using system.text; using system.runtime.interopservices; namespace consoleapplication5 { public class sharedtool : 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;//域控中的需要用:interactive = 2 private bool disposed; public sharedtool(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 { // close handle(s) if (pexistingtokenhandle != intptr.zero) closehandle(pexistingtokenhandle); if (pduplicatetokenhandle != intptr.zero) closehandle(pduplicatetokenhandle); } } protected virtual void dispose(bool disposing) { if (!disposed) { reverttoself(); disposed = true; } } public void dispose() { dispose(true); } } }
案例:
using system; using system.collections.generic; using system.linq; using system.text; using system.io; namespace consoleapplication5 { class program { static void main(string[] args) { using (sharedtool tool = new sharedtool("administrator", "12345678", "192.168.1.101")) { string selectpath = @"\\192.168.1.101\c$"; var dicinfo = new directoryinfo(selectpath);//选择的目录信息 directoryinfo[] dic = dicinfo.getdirectories("*.*", searchoption.topdirectoryonly); foreach (directoryinfo temp in dic) { console.writeline(temp.fullname); } console.writeline("---------------------------"); fileinfo[] textfiles = dicinfo.getfiles("*.*", searchoption.topdirectoryonly);//获取所有目录包含子目录下的文件 foreach (fileinfo temp in textfiles) { console.writeline(temp.name); } } console.readkey(); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。