SoFunction
Updated on 2025-03-07

How to open and read the file directory of usb

Below I will show you a small example and a code snippet. Friends in need can learn from it.

Drag a button and treeview on the interface, insert it directly into the USB flash drive when running, and the directory file will appear on the stand-alone button. However, the information can only be received when the USB drive is inserted and unplugged.
1.[C#] code

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
 namespace usbText
{
 public partial class Form1 : Form
 {
 DriveInfo Tdriver = null;
 public Form1()
 {
 InitializeComponent();
 }
 protected override void WndProc(ref Message m)
 {
 if ( == 0x0219)//WM_DEVICECHANGE
 {
 switch (.ToInt32())
 {
  case 0x8000://DBT_DEVICEARRIVAL
  {
  ("Device Insert");
  string[] dirs = (); //Get all drive letters  foreach (string dir in dirs)
  {
   Tdriver = new DriveInfo(dir);
   if ( == )
   {
   {
   while ( == false)
   {
   (500);
   }
   try
   {
   string PSTR = "";
   PSTR += "Disk Name:" +  + "\r\n";
   PSTR += "Disk Volume Tag:" +  + "\r\n";
   PSTR += "File System:" +  + "\r\n";
   PSTR += "Remaining size:" + () + "\r\n";
   PSTR += "Overall Capacity:" + () + "\r\n";
   PSTR += "Overall Capacity:" + () + "\r\n";
   (PSTR);
   }
   catch
   {
   ("error");
   }
   }
   }
  } 
  break;
  }
  case 0x8004://DBT_DEVICEREMOVECOMPLETE
  {
  ("Download device");
  break;
  }
 }
 }
 (ref m);
 }
 private void AddToTreeView(TreeNode node)
 {
 (node);
 ();
 }
 internal void LoadFolderFileList(string path, TreeNode nodes)
 {
 string[] dirs = (path);
 string[] files = (path);
 for (int i = 0; i < ; i++)
 {
 string[] info = new string[4];
 DirectoryInfo di = new DirectoryInfo(dirs[i]);
 TreeNode node = new TreeNode();
  = ;
 try
 {
  if (().Length > 0 || ().Length > 0)
  {
  LoadFolderFileList(, node);
  }
  else
  {
  continue;
  }
 }
 catch
 {
  continue;
 }
 (node);
 }
 for (int i = 0; i < ; i++)
 {
 FileInfo fi = new FileInfo(files[i]);
 TreeNode node = new TreeNode();
  = ;
 (node);
 }
 }
 private void button1_Click(object sender, EventArgs e)
 {
 if (Tdriver != null)
 {
 TreeNode node = new TreeNode();
 LoadFolderFileList((), node);
 (node);
 }
 }
 }
}

Through the above code, you can open and read the usb file directory. I hope you like it.