代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace _demo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void TraverseFolder(string folderPath)
{
try
{
// 获取文件夹中的所有子文件夹
string[] subDirectories = Directory.GetDirectories(folderPath);
// 遍历并输出文件夹信息到文本框中
foreach (string subDirectory in subDirectories)
{
DirectoryInfo directoryInfo = new DirectoryInfo(subDirectory);
string folderInfo = $"{directoryInfo.Name}{Environment.NewLine}{directoryInfo.FullName}{Environment.NewLine}{directoryInfo.CreationTime}{Environment.NewLine}{Environment.NewLine}";
outputTextBox.AppendText(folderInfo); // 使用 AppendText 方法追加内容到文本框
}
}
catch (Exception ex)
{
MessageBox.Show("发生错误:" + ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
string rootPath = @"C:\";
TraverseFolder(rootPath);
}
private void button2_Click(object sender, EventArgs e)
{
string newFolderPath = "C:\\NewFolder";
try
{
if (!Directory.Exists(newFolderPath))
{
Directory.CreateDirectory(newFolderPath);
MessageBox.Show("New folder created: " + newFolderPath);
string newFilePath = Path.Combine(newFolderPath, "newfile.txt");
File.Create(newFilePath);
MessageBox.Show("New file created: " + newFilePath);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
注意:记得引用system.IO,用于对文件夹的遍历。