C#如何打开并读取usb的文件目录
程序员文章站
2023-12-12 16:58:04
下面我通过一个小例子并结合一段代码片段给大家展示下,有需要的朋友可以来借鉴下。
界面上拖一个 button 和treeview ,运行的时候直接插入优盘,单机...
下面我通过一个小例子并结合一段代码片段给大家展示下,有需要的朋友可以来借鉴下。
界面上拖一个 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的文件目录,希望大家能够喜欢。