【问题标题】:System.IO dont create the file jsonSystem.IO 不创建文件 json
【发布时间】:2019-02-01 18:37:13
【问题描述】:

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

调试日志:

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)注意错误信息说:Could not find file "C:\Users\HP\AppData\LocalLow\NameName\BeautyGame\gamesettings.json ".注意这里提到的完整文件路径。 (2) 请注意,您发布的堆栈跟踪不完整。因此,为您准备了一个工作项:检查System.IO.File.WriteAllText 是否出现在完整的堆栈跟踪中。就个人而言,我怀疑您在此处显示的 File.WriteAllText 代码行导致了这个特定的“找不到文件”错误。检查您的项目中代码中以任何方式访问 gamesettings.json 文件的其他位置
  • P.S.如果堆栈跟踪不像我假设的那样不完整,请检查您得到的异常的 InnerException 属性。它可能包含另一个异常对象,其错误消息和堆栈跟踪可以揭示更多有用的信息......
  • 我尝试了所有这些东西。没有什么能帮到我。也许除了“System.IO”之外还有其他东西?这对我来说会更容易。我要补充一点,这是我与该单位的第一次接触。我知道这很愚蠢,但除了 LARGE 项目,我不知道任何其他编程语言。问候。
  • 那个文件夹真的存在吗?
  • 另外,考虑使用File.WriteAllText(Path.Join(Application.persistentDataPath, "gamesettings.json"), jsonData));

标签: c# unity3d system.io.file


【解决方案1】:

我建议宁愿使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多