繁体   English   中英

File.Create正在创建一个代表文件的文件夹

[英]File.Create is creating a folder instand of file

我正在编写一个将序列化类并将其保存到文件的函数,某些类必须保存在其他文件夹中。 我正在使用Unity和C#。 这是我的代码:

    public void save<T>(T data, string fileName) where T : class{
    if (fileName == "")
        Debug.Log ("Empty file path");
    FileStream file = null;
    try{
        if(fileName.IndexOf("/") > 0){
            string[] strDirName = fileName.Split(new char[]  {'/'});
            string dirName = strDirName[0];
            if(!Directory.Exists(Application.persistentDataPath + dirName)){
                Directory.CreateDirectory(Application.persistentDataPath + "/" + dirName);
            }
        }
        file = File.Create(constructFilePath(fileName));
        string a = constructFilePath(fileName);
        binFormatter.Serialize(file, data);
        Debug.Log ("File saved succesfully" + fileName);
    }catch(IOException e){
        Debug.Log(e.ToString());
    }finally{
        if(file != null)
            file.Close();
    }
}

string constructFilePath(string fileName){
    return Path.Combine(Application.persistentDataPath, fileName);
}

我不知道为什么要将文件保存为文件夹,这是因为我添加了以下代码来构造ConstructFilePath

if(fileName[0] != "/")
    fileName = "/" + fileName;

但是,如果没有此文件,它将创建其他文件夹。 它将Application.persistentDataPath与文件夹名称连接起来,并在那里创建文件,因此,如果我的persistentDataPath = C:/ Users / User / AppData / LocalLow / DefaultCompany / TestGame,并且我想将该文件存储在文件夹a中并存储文件b在里面

C:/Users/User/AppData/LocalLow/DefaultCompany/TestGame/a/b

它创建名称为TestGamea的文件夹并在其中存储b

 C:/Users/User/AppData/LocalLow/DefaultCompany/TestGamea/b

您正在评估一件事,并在此处执行不同的操作:

if(!Directory.Exists(Application.persistentDataPath + dirName)){
                Directory.CreateDirectory(Application.persistentDataPath + "/" + dirName);
            }

更改为:

if(!Directory.Exists(Path.Combine(Application.persistentDataPath, dirName))){
                Directory.CreateDirectory(Path.Combine(Application.persistentDataPath, dirName));
            }

就像Eric所说的那样,使用Path.Combine。 它将可靠地组合路径部分,并确保每次都能获得相同的结果,因此您不必担心字符串操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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