用c#写一个程序,当程序运行时,将最后一个固定磁盘根目录中的文件及一级文件夹中的全部文件路径存储到一个数组中,然后显示到文本框中
时间: 2024-03-09 09:45:08 浏览: 19
好的,以下是用 C# 实现的代码:
```csharp
using System;
using System.IO;
using System.Windows.Forms;
namespace LastDiskFiles
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string rootPath = GetLastFixedDiskRootPath();
string[] filePaths = GetFilePaths(rootPath);
ShowFilePaths(filePaths);
}
private string GetLastFixedDiskRootPath()
{
DriveInfo[] driveInfos = DriveInfo.GetDrives();
string lastFixedDiskRootPath = "";
foreach (DriveInfo driveInfo in driveInfos)
{
if (driveInfo.DriveType == DriveType.Fixed)
{
lastFixedDiskRootPath = driveInfo.RootDirectory.FullName;
}
}
return lastFixedDiskRootPath;
}
private string[] GetFilePaths(string rootPath)
{
string[] filePaths = Directory.GetFiles(rootPath);
string[] folderPaths = Directory.GetDirectories(rootPath);
foreach (string folderPath in folderPaths)
{
filePaths = filePaths.Union(GetFilePaths(folderPath)).ToArray();
}
return filePaths;
}
private void ShowFilePaths(string[] filePaths)
{
foreach (string filePath in filePaths)
{
textBox1.AppendText(filePath + Environment.NewLine);
}
}
}
}
```
这个程序有一个文本框(`textBox1`),程序加载时会自动获取最后一个固定磁盘的根目录,然后递归遍历该目录下的所有文件和一级文件夹,并将它们的路径存储到一个字符串数组中,最后将这个数组中的所有路径显示到文本框中。