C# 访问共享文件夹或者磁盘(需要用户名密码)

C# 访问共享文件夹或者磁盘(需要用户名密码)

边界流浪者

SharedTool:

  1. using System;

  2. using System.Collections.Generic;

  3. using System.Linq;

  4. using System.Text;

  5. using System.Runtime.InteropServices;

  6.  
  7. namespace ConsoleApplication5

  8. {

  9. public class SharedTool : IDisposable

  10. {

  11. // obtains user token

  12. [DllImport("advapi32.dll", SetLastError = true)]

  13. static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,

  14. int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

  15.  
  16. // closes open handes returned by LogonUser

  17. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]

  18. extern static bool CloseHandle(IntPtr handle);

  19.  
  20. [DllImport("Advapi32.DLL")]

  21. static extern bool ImpersonateLoggedOnUser(IntPtr hToken);

  22.  
  23. [DllImport("Advapi32.DLL")]

  24. static extern bool RevertToSelf();

  25. const int LOGON32_PROVIDER_DEFAULT = 0;

  26. const int LOGON32_LOGON_NEWCREDENTIALS = 9;//域控中的需要用:Interactive = 2

  27. private bool disposed;

  28.  
  29. public SharedTool(string username, string password, string ip)

  30. {

  31. // initialize tokens

  32. IntPtr pExistingTokenHandle = new IntPtr(0);

  33. IntPtr pDuplicateTokenHandle = new IntPtr(0);

  34.  
  35. try

  36. {

  37. // get handle to token

  38. bool bImpersonated = LogonUser(username, ip, password,

  39. LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);

  40.  
  41. if (bImpersonated)

  42. {

  43. if (!ImpersonateLoggedOnUser(pExistingTokenHandle))

  44. {

  45. int nErrorCode = Marshal.GetLastWin32Error();

  46. throw new Exception("ImpersonateLoggedOnUser error;Code=" + nErrorCode);

  47. }

  48. }

  49. else

  50. {

  51. int nErrorCode = Marshal.GetLastWin32Error();

  52. throw new Exception("LogonUser error;Code=" + nErrorCode);

  53. }

  54. }

  55. finally

  56. {

  57. // close handle(s)

  58. if (pExistingTokenHandle != IntPtr.Zero)

  59. CloseHandle(pExistingTokenHandle);

  60. if (pDuplicateTokenHandle != IntPtr.Zero)

  61. CloseHandle(pDuplicateTokenHandle);

  62. }

  63. }

  64.  
  65. protected virtual void Dispose(bool disposing)

  66. {

  67. if (!disposed)

  68. {

  69. RevertToSelf();

  70. disposed = true;

  71. }

  72. }

  73.  
  74. public void Dispose()

  75. {

  76. Dispose(true);

  77. }

  78. }

  79. }

 

案例:

 
  1. using System;

  2. using System.Collections.Generic;

  3. using System.Linq;

  4. using System.Text;

  5. using System.IO;

  6.  
  7. namespace ConsoleApplication5

  8. {

  9. class Program

  10. {

  11. static void Main(string[] args)

  12. {

  13. using (SharedTool tool = new SharedTool("administrator", "12345678", "192.168.1.101"))

  14. {

  15. string selectPath = @"\\192.168.1.101\c$";

  16.  
  17. var dicInfo = new DirectoryInfo(selectPath);//选择的目录信息

  18.  
  19. DirectoryInfo[] dic = dicInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly);

  20. foreach (DirectoryInfo temp in dic)

  21. {

  22. Console.WriteLine(temp.FullName);

  23. }

  24.  
  25. Console.WriteLine("---------------------------");

  26. FileInfo[] textFiles = dicInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);//获取所有目录包含子目录下的文件

  27. foreach (FileInfo temp in textFiles)

  28. {

  29. Console.WriteLine(temp.Name);

  30. }

  31. }

  32. Console.ReadKey();

  33. }

  34. }

  35. }

 

C# 通过用户名和密码获取共享文件夹访问权限

局域网共享文件夹需要用户名和密码才能访问,通过程序怎样才能获得文件夹访问权限呢?

这里主要利用了DOS命令中的“NET USE”命令来实现。

复制代码

public static void GetAccessControl(string path,string user,string pwd)
{       
      Process p = new Process();
            
      p.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");
            
      p.StartInfo.UseShellExecute = false;
      p.StartInfo.RedirectStandardInput = true;
      p.StartInfo.RedirectStandardOutput = true;
      p.StartInfo.CreateNoWindow = true;

      p.Start();           
      p.StandardInput.WriteLine(@"Net Use {0} /del", path); //必须先删除,否则报错
      p.StandardInput.WriteLine(@"Net Use {0} ""{1}"" /user:{2}", path, pwd, user);
      p.StandardInput.WriteLine("exit"); //如果不加这句WaitForExit会卡住

      p.WaitForExit();
      p.Close();
 }

你可能感兴趣的:(C#)