用c#写一个程序,当程序运行时,将最后一个固定磁盘根目录中的文件及一级文件夹中的全部文件路径存储到一个数组中,然后显示到文本框中
时间: 2024-03-09 22:44:35 浏览: 23
好的,以下是用 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[] files = GetLastDiskFiles();
foreach (string file in files)
{
textBox1.AppendText(file + Environment.NewLine);
}
}
private string[] GetLastDiskFiles()
{
string[] files = new string[0];
DriveInfo[] drives = DriveInfo.GetDrives();
if (drives.Length > 0)
{
DriveInfo lastDrive = drives[drives.Length - 1];
if (lastDrive.IsReady)
{
string rootPath = lastDrive.RootDirectory.FullName;
string[] subDirs = Directory.GetDirectories(rootPath);
string[] subFiles = Directory.GetFiles(rootPath);
files = new string[subDirs.Length + subFiles.Length];
Array.Copy(subDirs, files, subDirs.Length);
Array.Copy(subFiles, 0, files, subDirs.Length, subFiles.Length);
}
}
return files;
}
}
}
```
代码中通过 `DriveInfo.GetDrives()` 获取所有磁盘信息,然后取最后一个磁盘(根据字母排序),获取其根目录,再使用 `Directory.GetDirectories()` 和 `Directory.GetFiles()` 方法获取一级子文件夹和文件的路径,最后将它们合并到一个数组中。在窗体加载时,将数组中的路径显示到文本框中。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)