System.IO不要创建文件json

时间:2019-02-01 18:37:14

标签: c# unity3d system.io.file

System.IO不会使用保存游戏创建文件。 我尝试在管理员模式下运行统一性,什么也没做。

调试日志:

FileNotFoundException: Could not find file "C:\Users\HP\AppData\LocalLow\NameName\BeautyGame\gamesettings.json"
System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) (at <ac823e2bb42b41bda67924a45a0173c3>:0)
System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.IO.FileOptions options, System.String msgPath, System.Boolean bFromProxy, System.Boolean useLongPath, System.Boolean checkHost) (at <ac823e2bb42b41bda67924a45a0173c3>:0)
(wrapper remoting-invoke-with-check) System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,int,System.IO.FileOptions,string,bool,bool,bool)

和代码:

string jsonData = JsonUtility.ToJson(gameSettings, true);
File.WriteAllText(Application.persistentDataPath + "/gamesettings.json", jsonData));

1 个答案:

答案 0 :(得分:0)

我建议您宁可使用FileStreamStreamWriter并确保已设置FileMode.Create。如果该文件夹不存在,则还要创建它。

var folderPath = Application.persistentDataPath;

// Create directory if not exists
if (!Directory.Exists(folderPath))
{
    Directory.CreateDirectory(folderPath);
}

比起使用Path.Combine来创建与系统无关的路径字符串

var filePath = Path.Combine(folderPath, "gamesettings.json");

现在写入文件

// Create file or overwrite if exists
using (var file = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write))
{
    using (var writer = new StreamWriter(file, Encoding.UTF8))
    {
        writer.Write(content);
    }
}

但是,为了从UnityEditor在PC上进行本地测试,我不希望该应用将数据泄漏到我的开发PC中,而是将其放置在例如StreamingAssets,仅在内部版本中使用persistentDataPath

var folderPath =
#if !UNITY_EDITOR
     Application.persistentDataPath;
#else
     Application.streamingAssetsPath;
#endif