C# 获取电脑所有文件

有的电脑 需要安装 fromwor3.5

 

 

class Program
    {

        static List<string> filesa = new List<string>();
        List<string> files = new List<string>();
        static void Main(string[] args)
        {
            var aa = GetRemovableDeviceID();
            StringBuilder sb = new StringBuilder();
            
            Console.WriteLine(sb.ToString());
            foreach (var item in aa)
            {


                GetAllDirectories(item + "\\");
                
            }
            foreach (var item in filesa)
            {
                var da = sb.Append(item+Environment.NewLine);
            }

            File.WriteAllText("文件.txt", sb.ToString());




            Console.WriteLine("Ok");


            Console.ReadKey();
        }


        private static void GetAllDirectories(string rootPath)
        {

            DirectoryInfo di = new DirectoryInfo(rootPath);
            string attributes = di.Attributes.ToString();
           
            DirectorySecurity s = new DirectorySecurity(rootPath, AccessControlSections.Owner);

            //try
            //{

                
                //!s.AreAccessRulesProtected & 
                //判断目录是否 可以访问  Directory
                if (!s.AreAccessRulesProtected & !rootPath.Contains("Windows") &  !di.Attributes.ToString().Contains("NotContentIndexed") & (!di.Attributes.ToString().ToLower().Contains("hidden")|| rootPath.Contains("C")))//& !rootPath.Contains("Documents and Settings")
            {
                string[] subPaths = System.IO.Directory.GetDirectories(rootPath);//得到所有子目录

                foreach (string path in subPaths)

                {

                    try
                    {
                        Console.WriteLine(path);
                        GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List
                    }
                    catch (Exception ex)
                    {
                        
                        DirectoryInfo d2i = new DirectoryInfo(path);
                        string aaaa = d2i.Attributes.ToString();
                        var aa = !d2i.Attributes.ToString().ToLower().Contains("hidden");
                        //AddSecurityControll2File(path);
                        Console.WriteLine(path);

                        //GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List
                        //throw;
                    }
                    

                }

                string[] files = System.IO.Directory.GetFiles(rootPath);

                foreach (string file in files)
                {
                    Console.WriteLine(file);
                    filesa.Add(file);//将当前目录中的所有文件全名存入文件List

                }

            }
            //}
            //catch (Exception ex)
            //{

            //    Console.WriteLine(ex);
            //    Console.ReadKey();
            //}
        }




        static void AddSecurityControll2File(string filePath)
        {

            ////获取文件信息
            //FileInfo fileInfo = new FileInfo(filePath);
            ////获得该文件的访问权限
            //System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
            ////添加ereryone用户组的访问权限规则 完全控制权限
            //fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
            ////添加Users用户组的访问权限规则 完全控制权限
            //fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
            ////设置访问权限
            //fileInfo.SetAccessControl(fileSecurity);




            //FileInfo fi = new FileInfo(filePath);
            //System.Security.AccessControl.FileSecurity fileSecurity = fi.GetAccessControl();
            //fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
            //fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
            //fi.SetAccessControl(fileSecurity);

            ////给Excel文件所在目录添加"Everyone,Users"用户组的完全控制权限  
            //DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(filePath));
            //System.Security.AccessControl.DirectorySecurity dirSecurity = di.GetAccessControl();
            //dirSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
            //dirSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
            //di.SetAccessControl(dirSecurity);

        }




        public static List<string> GetRemovableDeviceID()
        {
            List<string> deviceIDs = new List<string>();
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT  *  From  Win32_LogicalDisk ");
            ManagementObjectCollection queryCollection = query.Get();
            foreach (ManagementObject mo in queryCollection)
            {

                switch (int.Parse(mo["DriveType"].ToString()))
                {
                    case (int)DriveType.Removable:   //可以移动磁盘       
                        {
                            //MessageBox.Show("可以移动磁盘");  
                            //deviceIDs.Add(mo["DeviceID"].ToString());
                            break;
                        }
                    case (int)DriveType.Fixed:   //本地磁盘       
                        {
                            //MessageBox.Show("本地磁盘");  
                            deviceIDs.Add(mo["DeviceID"].ToString());
                            break;
                        }
                    case (int)DriveType.CDRom:   //CD   rom   drives       
                        {
                            //MessageBox.Show("CD   rom   drives ");  
                            break;
                        }
                    case (int)DriveType.Network:   //网络驱动     
                        {
                            //MessageBox.Show("网络驱动器 ");  
                            break;
                        }
                    case (int)DriveType.Ram:
                        {
                            //MessageBox.Show("驱动器是一个 RAM 磁盘 ");  
                            break;
                        }
                    case (int)DriveType.NoRootDirectory:
                        {
                            //MessageBox.Show("驱动器没有根目录 ");  
                            break;
                        }
                    default:   //defalut   to   folder       
                        {
                            //MessageBox.Show("驱动器类型未知 ");  
                            break;
                        }
                }

            }
            return deviceIDs;
        }
    }

 

转载于:https://www.cnblogs.com/yuanzhifei/p/8927002.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要读取其他电脑文件,需要使用网络共享功能。以下是使用C#访问其他计算机上共享文件夹的步骤: 1. 确保目标计算机上的文件夹已设置为“共享”。 2. 在C#项目中添加对System.IO和System.Net命名空间的引用。 3. 使用NetworkCredential对象创建凭据对象,以便在访问共享文件夹时进行身份验证。 4. 使用UNC路径(例如 \\computername\sharedfolder)访问共享文件夹。 5. 使用File类或Directory类的方法访问共享文件夹中的文件文件夹。 以下是一个示例代码: ``` using System; using System.IO; using System.Net; class Program { static void Main(string[] args) { string path = @"\\computername\sharedfolder\myfile.txt"; NetworkCredential credentials = new NetworkCredential("username", "password"); using (new NetworkConnection(path, credentials)) { // 访问共享文件夹中的文件 string content = File.ReadAllText(path); Console.WriteLine(content); } } } // NetworkConnection类,用于创建网络连接 public class NetworkConnection : IDisposable { private readonly string _networkName; public NetworkConnection(string networkName, NetworkCredential credentials) { _networkName = networkName; var netResource = new NetResource { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplayType.Share, RemoteName = networkName }; var result = WNetAddConnection2( netResource, credentials.Password, $"{credentials.Domain}\\{credentials.UserName}", 0); if (result != 0) { throw new IOException($"Failed to connect to {_networkName}. Error: {result}"); } } ~NetworkConnection() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { WNetCancelConnection2(_networkName, 0, true); } [System.Runtime.InteropServices.DllImport("mpr.dll")] private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flags); [System.Runtime.InteropServices.DllImport("mpr.dll")] private static extern int WNetCancelConnection2(string name, int flags, bool force); } // NetResource类,用于设置网络资源的属性 public class NetResource { public ResourceScope Scope { get; set; } public ResourceType ResourceType { get; set; } public ResourceDisplayType DisplayType { get; set; } public int Usage { get; set; } public string LocalName { get; set; } public string RemoteName { get; set; } public string Comment { get; set; } public string Provider { get; set; } } // 枚举类型,用于指定网络资源的范围、类型和显示方式 public enum ResourceScope : int { Connected = 1, GlobalNetwork, Remembered, Recent, Context } public enum ResourceType : int { Any = 0, Disk = 1, Print = 2, Reserved = 8, } public enum ResourceDisplayType : int { Generic = 0x0, Domain = 0x01, Server = 0x02, Share = 0x03, File = 0x04, Group = 0x05, Network = 0x06, Root = 0x07, Shareadmin = 0x08, Directory = 0x09, Tree = 0x0a, Ndscontainer = 0x0b } ``` 在上面的代码中,使用了一个名为“NetworkConnection”的自定义类,用于创建网络连接。该类使用WNetAddConnection2函数创建网络连接,并在不再需要时使用WNetCancelConnection2函数取消网络连接。使用using语句块创建NetworkConnection对象,以确保在使用完毕后自动释放资源。 请注意,为了访问共享文件夹,必须提供正确的凭据对象。在上面的示例代码中,使用NetworkCredential对象传递用户名和密码。如果目标计算机不需要凭据,则可以省略NetworkCredential对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值