3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# で再帰的にファイルを探す処理を書いてみた

Posted at

最初にお断りするのですが、↓のオプションをちゃんと使えばだいたい同じことができます。
https://docs.microsoft.com/ja-jp/dotnet/api/system.io.directory.getfiles?view=netframework-4.8

まぁなんとなくイメージできたから書いてみたかった、という程度の理由で自前実装しました。


    public void Main()
    {
        var root = "Assets/StreamingAssets/";
        var paths = new List<string>();

        // txt パスをリストに追加する
        Action<string> action = (path) =>
        {
            if (path.EndsWith(".txt")) { paths.Add(path); }
        };
        CollectPath(root, action);

        foreach (var path in paths)
        {
            // 各パスに対してやりたいこと
            Debug.Log(path);
        }
    }

    private void CollectPath(string root, Action<string> action)
    {
        var dirPaths = Directory.GetDirectories(root);
        foreach (var path in dirPaths)
        {
            // 末尾に \ が付くのを回避(★)
            var p = path + "/";
            CollectPath(p, action);
        }

        var filePaths = Directory.GetFiles(root);
        foreach (var path in filePaths)
        {
            action(path);
        }
    }

rootの値でピンとくる人も多いと思いますが、Unity 用の実装です。
環境が Windows のため何もしないと区切りが \ になってしまうので、★のところで無理やり対処しています。

3
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?