用c#编写一基于Windows From的程序,实现对C盘根目录文件夹的遍历,打印文件夹信息。并新建一文件夹,在文件夹中创建一文本文件。

代码如下: 

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,用于对文件夹的遍历。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值