C#若何翻開並讀取usb的文件目次。本站提示廣大學習愛好者:(C#若何翻開並讀取usb的文件目次)文章只能為提供參考,不一定能成為您想要的結果。以下是C#若何翻開並讀取usb的文件目次正文
上面我經由過程一個小例子並聯合一段代碼片斷給年夜家展現下,有須要的同伙可以來自創下。
界面上拖一個 button 和treeview ,運轉的時刻直接拔出優盤,單機按鈕就會湧現目次文件。不外只能在u盤拔出,U盤拔出時,能力吸收到信息。
1.[C#]代碼
using System; using System.Collections; 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; using System.Threading.Tasks; using System.Windows.Forms; namespace usbText { public partial class Form1 : Form { DriveInfo Tdriver = null; public Form1() { InitializeComponent(); } protected override void WndProc(ref Message m) { if (m.Msg == 0x0219)//WM_DEVICECHANGE { switch (m.WParam.ToInt32()) { case 0x8000://DBT_DEVICEARRIVAL { MessageBox.Show("裝備拔出"); string[] dirs = Environment.GetLogicalDrives(); //獲得一切的盤符 foreach (string dir in dirs) { Tdriver = new DriveInfo(dir); if (Tdriver.DriveType == DriveType.Removable) { { while (Tdriver.IsReady == false) { Thread.Sleep(500); } try { string PSTR = ""; PSTR += "磁盤稱號:" + Tdriver.Name + "\r\n"; PSTR += "磁盤卷標:" + Tdriver.VolumeLabel + "\r\n"; PSTR += "文件體系:" + Tdriver.DriveFormat + "\r\n"; PSTR += "殘剩年夜小:" + Tdriver.AvailableFreeSpace.ToString() + "\r\n"; PSTR += "整體容量:" + Tdriver.TotalSize.ToString() + "\r\n"; PSTR += "整體容量:" + Tdriver.RootDirectory.ToString() + "\r\n"; MessageBox.Show(PSTR); } catch { MessageBox.Show("error"); } } } } break; } case 0x8004://DBT_DEVICEREMOVECOMPLETE { MessageBox.Show("裝備拔出"); break; } } } base.WndProc(ref m); } private void AddToTreeView(TreeNode node) { treeView1.Nodes.Add(node); treeView1.Refresh(); } internal void LoadFolderFileList(string path, TreeNode nodes) { string[] dirs = Directory.GetDirectories(path); string[] files = Directory.GetFiles(path); for (int i = 0; i < dirs.Length; i++) { string[] info = new string[4]; DirectoryInfo di = new DirectoryInfo(dirs[i]); TreeNode node = new TreeNode(di.Name); node.Tag = di.FullName; try { if (di.GetDirectories().Length > 0 || di.GetFiles().Length > 0) { LoadFolderFileList(di.FullName, node); } else { continue; } } catch { continue; } nodes.Nodes.Add(node); } for (int i = 0; i < files.Length; i++) { FileInfo fi = new FileInfo(files[i]); TreeNode node = new TreeNode(fi.Name); node.Tag = fi.FullName; nodes.Nodes.Add(node); } } private void button1_Click(object sender, EventArgs e) { if (Tdriver != null) { TreeNode node = new TreeNode(); LoadFolderFileList(Tdriver.RootDirectory.ToString(), node); treeView1.Nodes.Add(node); } } } }
經由過程以上代碼可以完成翻開並讀取usb的文件目次,願望年夜家可以或許愛好。