开发者

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;
us开发者_JAVA百科ing 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();
    }
}


If you have .NET 4.0, you can save yourself a lot of trouble by using 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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜