C# 文件。创建正在创建文件的文件夹实例

C# 文件。创建正在创建文件的文件夹实例,c#,C#,我正在编写一个函数,它将序列化类并将其保存到文件中,有些类必须保存在不同的文件夹中。我用的是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(fileN

我正在编写一个函数,它将序列化类并将其保存到文件中,有些类必须保存在不同的文件夹中。我用的是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);
}
但是没有这个文件,它会创建不同的文件夹。它将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。它将可靠地组合路径部分,并确保每次都得到相同的结果,因此您不必担心字符串操作。

您可以使用path.combine而不是您自己的constructFilePath。使用
path.combine
它将为您处理前导斜杠和尾随斜杠,例如
path.combine(“C:\My\path\”,“\My\file.txt”)
结果是
C:\My\Path\My\file.txt
谢谢大家,但现在它只是在文件名前添加了一个/,你知道为什么吗?用当前实现更新代码。很抱歉,我忘了更新代码。
if(!Directory.Exists(Path.Combine(Application.persistentDataPath, dirName))){
                Directory.CreateDirectory(Path.Combine(Application.persistentDataPath, dirName));
            }