博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
获取局域网中指定IP或是主机名称的所有文件夹及其搜索文件
阅读量:5093 次
发布时间:2019-06-13

本文共 3991 字,大约阅读时间需要 13 分钟。

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

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

    } }

转载于:https://www.cnblogs.com/-ioricn/p/3867756.html

你可能感兴趣的文章
iis 下的 selfssl
查看>>
什么样的公司卖什么货!
查看>>
cassandra vs mongo (1)存储引擎
查看>>
[原创]BizTalk 开发系列
查看>>
uva10382
查看>>
Visual Studio基于CMake配置opencv1.0.0、opencv2.2
查看>>
常见编程语言入口特征
查看>>
[Leetcode 94] 72 Binary Tree Inorder Traversal
查看>>
Vue音乐项目笔记(三)
查看>>
遍历Map对象
查看>>
计算剪贴板里仿制的代码行数
查看>>
YTU 2578: 分数减法——结构体
查看>>
MySQL索引背后的数据结构及算法原理
查看>>
面向对象程序设计 作业一
查看>>
POJ 3360 H-Cow Contest
查看>>
#Leetcode# 209. Minimum Size Subarray Sum
查看>>
2019省赛训练组队赛4.11周四 2014浙江省赛
查看>>
HDU 2084 数塔
查看>>
android 界面切换【转】
查看>>
JavaScript我学之七数组
查看>>