简体   繁体   English

C#遍历文件帮助

[英]C# Iterate Through Files Help

I currently have code to iterate through files on my computer, although I am trying to hook up the Button.Click event to execute this, how would I do this? 我现在有代码可以遍历计算机上的文件,尽管我试图连接Button.Click事件来执行此操作,我该怎么做? And where would the output go? 输出将输出到哪里?

Code below: 代码如下:

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
}


public class FileSystemList : IEnumerable<string>
{
    DirectoryInfo rootDirectory;

    public FileSystemList(string root)
    {
        rootDirectory = new DirectoryInfo(root);
    }

    public IEnumerator<string> GetEnumerator()
    {
        return ProcessDirectory(rootDirectory).GetEnumerator();
    }

    public IEnumerable<string> ProcessDirectory(DirectoryInfo dir)
    {
        yield return dir.FullName;
        foreach (FileInfo file in dir.EnumerateFiles())
            yield return file.FullName;
        foreach (DirectoryInfo subdir in dir.EnumerateDirectories())
            foreach (string result in ProcessDirectory(subdir))
                yield return result;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

如果您使用的是.NET 4.0,则可以使用Directory.EnumerateFiles节省很多麻烦。

You need to instantiate a FileSystemList object in your button click event handler, call the methods you need on it (a foreach loop seems likely). 您需要在按钮单击事件处理程序中实例化FileSystemList对象,在其上调用所需的方法(似乎有foreach循环)。

As for the results - put the output where you want it. 至于结果-将输出放在所需的位置。 It goes where you, as a programmer, want it to go. 它是您作为程序员希望去的地方。

var list = new FileSystemList(pathIWantToList);
foreach(var item in list)
{
  // do something
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM