首页 > 代码库 > 获取局域网中指定IP或是主机名称的所有文件夹及其搜索文件

获取局域网中指定IP或是主机名称的所有文件夹及其搜索文件

最近做个功能在局域网中所有指定文件,于是花了点精力完成了部分功能,先贴上

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data; using System.Drawing;

using System.IO; using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Collections;

using System.Runtime.InteropServices;

using System.Diagnostics;

namespace QuickSearchToolsInNet {    

public partial class Form1 : Form     {        

public Form1()         {            

InitializeComponent();        

}

             private void btnSearch_Click(object sender, EventArgs e)         {       

      #region 此部分主要为了测试一台计算机,数量太多搜索速度会很慢          

   IList<string> lstIps = GetIpsByGroup();           

  string ip = @"\\ckf4989v";           

  string selectPath = @"c:\";            

foreach (var item in lstIps)             {               

  if (item.ToLower().Contains(ip))                 {                     selectPath = ip + @"\";                 }             }         

    #endregion            

string[] ShareList = NetShareList(selectPath);            

FileInfo[] textFiles = null;            

Array.ForEach(ShareList, Share => {                

string sharePath = selectPath + Share;                

var dicInfo = new DirectoryInfo(sharePath);//选择的目录信息                

textFiles = dicInfo.GetFiles("*.*", SearchOption.AllDirectories);          

   });            

StringBuilder sb = new StringBuilder();            

if (textFiles!=null)             {               

  foreach (var item in textFiles)                 {                   

  sb.Append(item.FullName+"\r\n");                

}             }            

this.richTextBox1.Text = sb.ToString();

            //DirectoryInfo dir = new DirectoryInfo(ip);         

    //StringBuilder sb = Getfiless(dir);           

  //MessageBox.Show(sb.ToString());     

    }              

   #region   获取局域网中某个计算机的所有共享文件夹     

    [StructLayout(LayoutKind.Sequential)]       

  protected struct SHARE_INFO_1         {            

  [MarshalAs(UnmanagedType.LPWStr)]            

public string shi1_netname;          

   [MarshalAs(UnmanagedType.U4)]           

  public uint shi1_type;            

[MarshalAs(UnmanagedType.LPWStr)]          

   public string shi1_remark;        

}       

  [DllImport("Netapi32.dll", EntryPoint = "NetShareEnum")]      

   protected static extern int NetShareEnum(        

[MarshalAs(UnmanagedType.LPWStr)] string servername,      

   [MarshalAs(UnmanagedType.U4)] uint level,         out IntPtr bufptr,       

  [MarshalAs(UnmanagedType.U4)] int prefmaxlen,        

[MarshalAs(UnmanagedType.U4)] out uint entriesread,       

  [MarshalAs(UnmanagedType.U4)] out uint totalentries,        

[MarshalAs(UnmanagedType.U4)] out uint resume_handle       

  );        

private string[] NetShareList(string server)         {

            IntPtr buffer;             uint entriesread;             uint totalentries;             uint resume_handle;

            //-1应该是获取所有的share,msdn里面的例子是这么写的,返回0表示成功            

if (NetShareEnum(server, 1, out buffer, -1, out entriesread, out totalentries, out resume_handle) == 0)             {          

       Int32 ptr = buffer.ToInt32();                

ArrayList alShare = new ArrayList();           

      for (int i = 0; i < entriesread; i++)                 {

                    SHARE_INFO_1 shareInfo = (SHARE_INFO_1)Marshal.PtrToStructure(new IntPtr(ptr), typeof(SHARE_INFO_1));                     if (shareInfo.shi1_type == 0)//Disk drive类型                     {                        

alShare.Add(shareInfo.shi1_netname);                   

  }                  

   ptr += Marshal.SizeOf(shareInfo);//有点类似C代码               

  }                

string[] share = new string[alShare.Count];            

     for (int i = 0; i < alShare.Count; i++)                 {                     share[i] = alShare[i].ToString();                 }                 return share;             }            

else                 return null;

        }      

   #endregion

        #region 获取工作组中所有计算机名        

private IList<string> GetIpsByGroup()         {         

    ProcessStartInfo info = new ProcessStartInfo("cmd.exe");           

  info.Arguments = "/k net view";            //不使用壳来执行进程,才能捕获输入输出流                

        info.UseShellExecute = false;            //重定向输入流                   

    //info.RedirectStandardInput = true;                            

  info.RedirectStandardOutput = true;      //重定向输出流           

      Process p = Process.Start(info);            

StreamReader output = p.StandardOutput;     //获取输出流的操作Writer         

    IList<string> lstIps = new List<string>();            

while (!output.EndOfStream)             {                 string line = output.ReadLine();                 if (line.StartsWith("\\\\"))                     lstIps.Add(line);             }             return lstIps;         }        

#endregion

 

        #region 递归获取某个目录下的所有文件(包含子目录中的文件)------------------已废弃      

   /// <summary>         /// 递归获取某个目录下的所有文件(包含子目录中的文件)------------------已废弃         /// </summary>    

     /// <param name="dir">最外层文件夹路径</param>        

/// <returns></returns>       

  private StringBuilder Getfiless(DirectoryInfo dir)         {            

FileInfo[] files = dir.GetFiles();           

  StringBuilder sb = new StringBuilder();          

   foreach (var item in files)             {               

  sb.Append(item.FullName + "\r\n");         

    }          

   if (dir.GetDirectories().Length > 0)             {                

DirectoryInfo[] dirs = dir.GetDirectories();               

  foreach (var item in dirs)                 {                

     sb.Append(Getfiless(item) + "\r\n");              

   }             }            

return sb;         }

        #endregion

    } }