How does C open and read the file directory of usb
- 2021-07-10 20:36:44
- OfStack
Below I through a small example and combined with a fragment of code to show you under the need of friends can learn from it.
Drag 1 button and treeview on the interface, insert USB flash drive directly when running, and the directory file will appear on the stand-alone button. However, information can only be received when u disk is inserted and U disk is unplugged.
1. [C #] Code
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(" Device insertion ");
string[] dirs = Environment.GetLogicalDrives(); // Get all the drive letters
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 += " Disk name: " + Tdriver.Name + "\r\n";
PSTR += " Disk Volume Label: " + Tdriver.VolumeLabel + "\r\n";
PSTR += " File system: " + Tdriver.DriveFormat + "\r\n";
PSTR += " Remaining size: " + Tdriver.AvailableFreeSpace.ToString() + "\r\n";
PSTR += " Total capacity: " + Tdriver.TotalSize.ToString() + "\r\n";
PSTR += " Total capacity: " + Tdriver.RootDirectory.ToString() + "\r\n";
MessageBox.Show(PSTR);
}
catch
{
MessageBox.Show("error");
}
}
}
}
break;
}
case 0x8004://DBT_DEVICEREMOVECOMPLETE
{
MessageBox.Show(" Equipment pull-out ");
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);
}
}
}
}
Through the above code can be opened and read usb file directory, I hope you can like it.