LoginSignup
12
11

More than 5 years have passed since last update.

C#でフォルダ内のすべてのファイルを取得してツリーを記述する処理書いたんで自分用にメモ((φ(・д・。)

Last updated at Posted at 2016-02-29

Unityでプラグインを作成したり、パッケージングした時に、 ReadMeを作らなければならない事が多く、
毎回ファイルツリー書いてるのアホみたいなので、いい加減自動化した。
出力はUnityのDebug.Logでやってるけど、別の書き方すればおk。

ロジックは使えまわせそうなので、メモ

出力結果

Assets
    ┣ Dir1/
    ┃ ┣ File11
    ┃ ┣ File12
    ┃ ┣ File13
    ┃ ┣ Dir14/
    ┃ ┃ ┣ Dir141/
    ┃ ┃ ┃ ┣ File1411
    ┃ ┃ ┃ ┣ File1412
    ┃ ┃ ┃ ┣ File1413
    ┃ ┃ ┃ ┣ File1412
    ┃ ┃ ┗ Dir142/
    ┃ ┃     ┗ File1421
    ┃ ┗ Dir15/
    ┃     ┗ File151
    ┗ Dir2/
        ┗ File21

実際の処理

関数名が適当なのはご愛嬌。

Sample.cs
    public static void aaaa()
    {
        string result = "";
        GetFileTree ( ref result );
        Debug.Log( result );
    }

    private static void GetFileTree( ref string result, string root = null, string ex = "" )
    {
        // folder 
        if( root == null )
        {   
            root = Application.dataPath;
            result += getFile( root );
            ex += "\t";
        }
        string[] paths = Directory.GetDirectories( root, "*", SearchOption.TopDirectoryOnly );
        string[] files = Directory.GetFiles( root, "*", SearchOption.TopDirectoryOnly );
        List<string> children = new List<string>();
        children.AddRange(files);
        children.AddRange(paths);
        children.RemoveAll((s) => { return s.EndsWith( ".meta" ); } );
        for( int i = 0; i < children.Count; ++i )
        {
            string prefix = ex;
            string path  = children[i];
            // pathがフォルダかどうか
            bool   isDir = File.GetAttributes( path ).Equals( FileAttributes.Directory );
            // 第五のファイルかどうか
            bool   isEnd = i == children.Count - 1;
            if( isDir )
            {
                // フォルダなので、自分をRootに再帰呼び出し。
                if( !isEnd )
                {
                    result += "\n" + ex + "┣ " + getFile( path ) + "/";
                    prefix += "┃\t";
                }
                else
                {
                    result += "\n" + ex + "┗ " + getFile( path ) + "/";
                    prefix += "\t";
                }

                GetFileTree( ref result, path, prefix );
            }
            else
            {

                // ファイルなので、ファイル名を記述
                result += "\n" + ex + ( isEnd ? "┗ " : "┣ " ) + getFile( path );
            }
        }

    }

    private static string getFile( string path )
    {
        string[] strs = path.Split( "/"[0] );
        if( path.EndsWith( "/" ) )
        {
            return strs[ strs.Length - 2 ];
        }
        return strs[ strs.Length-1 ];
    }
12
11
0

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
12
11