简体   繁体   中英

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? 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).

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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