我想制作一个程序来读取系统中的驱动器总数并制作列表视图以显示其信息,即计算每个驱动器中存在的文件夹和文件的数量,并且由于哪个我有一些错误我无法解决这个问题。请帮我找到相同的错误。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using SystemInformation;
using SystemInformation.Properties;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Diagnostics;
using System.IO;
namespace SystemInformation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
ListViewItem item = new ListViewItem();
var k = Console.WriteLine(drive.Name);
item.SubItems.Add(k);
foreach (string path in Directory.EnumerateFiles(drive.Name))
{
Console.WriteLine(path);
lstInfo.Items.Add(item);
}
}
}
catch (MySqlException ex)
{
Trace.WriteLine(ex.Message);
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
}
public string k { get; set; }
}
}
答案 0 :(得分:0)
首先,Console.WriteLine()方法是无效的,你无法从中获取输出。
使用listview无法执行多个级别。您将需要使用TreeView。
以下代码将为您提供计算机上的文件结构:
private void Form1_Load(object sender, EventArgs e)
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
var item = TV_Items.Nodes.Add(drive.Name);
AddDirectories(item, drive.Name);
}
}
private void AddDirectories(TreeNode parent, string path)
{
var directories = Directory.GetDirectories(path);
foreach (var directory in directories)
{
try
{
var subItem = parent.Nodes.Add(Path.GetDirectoryName(directory));
foreach (var file in Directory.GetFiles(directory))
{
subItem.Nodes.Add(Path.GetFileNameWithoutExtension(file));
}
AddDirectories(subItem, directory);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
我不明白你想要什么。它是每个文件夹中或每个驱动器中的文件夹和文件的数量吗?