这篇文章主要介绍了用C#语言实现打开并读取usb的文件目录,但是实现此功能要注意一点必须在u盘插入才能接受到信息,需要的朋友可以参考下
下面我通过一个小例子并结合一段代码片段给大家展示下,有需要的朋友可以来借鉴下。
界面上拖一个 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的文件目录,希望大家能够喜欢。
新闻热点
疑难解答