Unity中使用File和Directory类操作文件和文件夹实例验证

验证点和注意点都在代码里面:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;

public class Test
{
    //public static string dirPath = Application.dataPath + "/AAA/BBB/CCC";
    public static string dirPath = Application.dataPath + "/AAA/BBB/CCC/ddd.txt";
    [MenuItem("Tools/CreateDirectory", false, 0)]
    public static void CreateDirectory()
    {
        //验证一:是否可以创建多层文件夹,答案:是
        //验证二:是否可以创建文件(比如上面的ddd.txt),答案:否
        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
            //AssetDatabase.SaveAssets();//没有这一句不会报错
            AssetDatabase.Refresh();//创建成功后要刷新才能马上看到
        }
    }

    public static string dirPathA = Application.dataPath + "/AAA";
    [MenuItem("Tools/DeleteDirectory", false, 1)]
    public static void DeleteDirectory()
    {
        if (Directory.Exists(dirPathA))
        {
            //通过上面创建的Application.dataPath + "/AAA/BBB/CCC/ddd.txt"这个目录结构,删除的打印如下
            //验证:DirectoryInfo对象获取的文件夹和文件都只是当前传入路径的子级目录中的,不包括孙子级的(这个验证错误了,DirectoryInfo也获取到了所有子集目录文件信息)
            //获取到的啥需要根据传递的参数来决定的
            DirectoryInfo info = new DirectoryInfo(dirPathA);
            //DirectoryInfo[] dir = info.GetDirectories();//只能获取子级下的目录信息
            DirectoryInfo[] dir = info.GetDirectories("*", SearchOption.AllDirectories);//能获取所有子级下的目录信息
            for (int i = 0; i < dir.Length; i++)
            {
                Debug.LogFormat("dir.Length[{0}] = {1}", i, dir[i].Name);//仅有文件夹名称
                Debug.LogFormat("dir.Length[{0}] = {1}", i, dir[i].ToString());//包含文件名称和后缀的全路径
                //dir[i].Delete(true);//dir.Length[0] = BBB
            }
            //FileInfo[] files = info.GetFiles();//只能获取子级下的文件信息
            FileInfo[] files = info.GetFiles("*",SearchOption.AllDirectories);//能获取所有子级下的文件信息
            for (int i = 0; i < files.Length; i++)
            {
                Debug.LogFormat("files.Length[{0}] = {1}", i, files[i].Name);//仅有文件名称和后缀
                Debug.LogFormat("files.Length[{0}] = {1}", i, files[i].ToString());//包含文件名称和后缀的全路径
                //files[i].Delete();//files.Length[0] = BBB.meta
            }
            AssetDatabase.Refresh();
        }
    }

    [MenuItem("Tools/GetFile", false, 2)]
    public static void GetFile()
    {
        //验证:"*.unity3d"是不是文件后缀,答案:是(即文件名包含了.unity3d但是不在末尾也会找不到)
        //验证:Path.GetDirectoryName获取的是当前文件或者文件夹的父目录路径(即文件或者文件夹的父目录都可以获取)
        string[] files = Directory.GetFiles(Application.dataPath + "/Package", "*.unity3d",SearchOption.AllDirectories);//获取的是包括子文件夹中的文件全路径,路径包含文件后缀
        for (int i = 0; i < files.Length; ++i)
        {
            Debug.Log("fileName:" + files[i]);
            Debug.Log("directoryName1:" + Path.GetDirectoryName(files[i]));//获取文件父目录
            Debug.Log("directoryName:2" + Path.GetDirectoryName(Path.GetDirectoryName(files[i])));//获取文件夹父目录
        }
    }


    //public static string filePath = Application.dataPath + "/EEE/FFF/GGG.txt";
    public static string filePath = Application.dataPath + "/GGG.txt";
    [MenuItem("Tools/CreateFile", false, 3)]
    public static void CreateFile()
    {
        //验证一:是否可以在不存在的路径下创建文件,答案:否
        //验证二:在存在的文件夹下创建文件,不执行AssetDatabase.SaveAssets()保存资源会不会报错,答案:会
        if (!File.Exists(filePath))
        {
            File.Create(filePath);
            AssetDatabase.SaveAssets();//没有这一句会报错
            AssetDatabase.Refresh();//创建成功后要刷新才能马上看到
        }
    }

    //public static string direcPath = Application.dataPath + "/AAA";
    public static string direcPath = Application.dataPath + "/AAA/BBB/CCC/ddd.txt";
    [MenuItem("Tools/GetDirectory", false, 4)]
    public static void GetDirectory()
    {
        //验证:Replace能否匹配大小写不一致的字符串?答案:不能
        string a = direcPath.Replace("aAA", "YYY");
        Debug.Log(a);
        //验证一:SearchOption.TopDirectoryOnly搜索模式不能获取到自己的路径,只能获取到下一级的文件夹目录,如果没有下一级文件夹则返回空
        //Debug.LogFormat("Directory.Exists(direcPath) = {0} , {1}", Directory.Exists(direcPath), direcPath);
        if (Directory.Exists(direcPath))
        {
            string[] folderList = Directory.GetDirectories(direcPath, "*", SearchOption.TopDirectoryOnly);
            for (int i = 0; i < folderList.Length; i++)
            {
                Debug.LogFormat("folderList[{0}] = {1}", i, folderList[i]);
            }
        }
    }


    [MenuItem("Tools/GetDirectory", false, 5)]
    public static void SortString()
    {
        string[] strs = new string[4] { "0_AA", "1_BB","4_DD","3_CC" };
        System.Array.Sort(strs, new SortByVersion());
        for (int i = 0; i < strs.Length; i++)
        {
            Debug.Log(strs[i]);
        }

        //变成了{ "4_DD","3_CC", "1_AA", "0_BB" };
    }

    private class SortByVersion : IComparer<string>
    {
        int IComparer<string>.Compare(string x, string y)
        {
            return y.Substring(0, y.LastIndexOf("_")).CompareTo(x.Substring(0, x.LastIndexOf("_")));
        }
    }


    /// <summary>
    /// 资源序列化:这个是不需要给类和变量增加任何序列化标签的,继承自ScriptableObject后它们会自动拥有可序列化的性质
    /// CreateAssetMenu标签:创建一个Assets/Create目录下的菜单选项,用于创建一个.asset文件
    /// fileName:要创建的资源名称
    /// menuName:Assets栏菜单名称
    /// order:菜单按钮所在层级
    /// ScriptableObject类:如果要创建不需要附加到游戏对象的对象,则可以派生一个类。
    /// </summary>
    [CreateAssetMenu(fileName = "assetbundlemap", menuName = "CreateAssetFile", order = 0)]//创建出来的文件位置处于当前选中的文件夹下面
    //[CreateAssetMenu(fileName = "Assets/Resources/assetbundlemap", menuName = "CreateAssetFile", order = 0)]//这种也可以指定路径创建
    public class AssetbundleConfig : ScriptableObject
    {

    }

    [MenuItem("Tools/CreateAsset", false, 6)]
    public static void CreateAsset()
    {
        //继承于ScriptableObject的类也可以通过CreateAsset来创建一个.asset文件
        AssetbundleConfig aa = ScriptableObject.CreateInstance<AssetbundleConfig>();//实例化类的对象
        AssetDatabase.CreateAsset(aa, "Assets/assetbundlemap.asset");//创建文件并将实例对象中的数据写入;
    }


    private static string srcPath = Application.dataPath + "/Package/scriptx32.unity3d";
    private static string disPath = Application.dataPath + "/StreamingAssets/aaa.bytes";
    [MenuItem("Tools/CopyFile", false, 7)]
    public static void CopyFile()
    {
        //验证:复制文件实际是直接创造了一个文件,而不是复制的类容
        System.IO.File.Copy(srcPath, disPath, true);
        AssetDatabase.Refresh();

        Debug.Log("Path.GetFileName(Application.dataPath + /Package/scriptx32.unity3d)" + Path.GetFileName(srcPath));
    }


    [MenuItem("Tools/PrintStreamingAssetsPath", false, 8)]
    public static void PrintStreamingAssetsPath()
    {
        //验证:Application.streamingAssetsPath是绝对路径
        Debug.Log("直接打印Application.streamingAssetsPath = " + Application.streamingAssetsPath);
    }


    [MenuItem("Tools/PrintFileName", false, 9)]
    public static void PrintFileName()
    {
        //验证:打印获取到的文件名包括了后缀
        Debug.Log("Path.GetFileName(Application.dataPath + /Package/scriptx32.unity3d) = " + Path.GetFileName(srcPath));
    }
}

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值