c# - UnauthorizedAccessException:将统一数据保存到文件时访问路径
问题描述
我有一个库存系统,它保存在一个文件中,并在需要时从同一个文件中加载。问题是加载系统在启动时完美运行但是当我按下保存和退出按钮时,它应该保存库存并加载主菜单场景,它会抛出 UnauthorizedAccessException: Access to the path 异常,即使文件未设置为只读,并且加载和保存的savePath相同:
public void Load()
{
if (File.Exists(string.Concat(Application.persistentDataPath, savePath)))
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(string.Concat(Application.persistentDataPath, savePath), FileMode.Open, FileAccess.Read);
Inventory newContainer = (Inventory)formatter.Deserialize(stream);
for (int i = 0; i < container.items.Length; i++)
{
container.items[i].UpdateSlot(newContainer.items[i].item, newContainer.items[i].amount);
}
stream.Close();
}
}
启动功能:
private void Start()
{
LoadInventory();
}
private void LoadInventory()
{
inventory.Load();
equipment.Load();
}
保存功能:
public void Save()
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(string.Concat(Application.persistentDataPath, savePath), FileMode.Create, FileAccess.Write);
formatter.Serialize(stream, container);
stream.Close();
}
以及调用保存函数的位置。构建游戏时 SceneManager.LoadScene(0); 行不运行:
public void SaveAndExit()
{
Time.timeScale = prevTimeScale;
SaveInventory();
SceneManager.LoadScene(0);
}
private void SaveInventory()
{
inventory.Save();
equipment.Save();
}
检查器中的 savePath 值
奇怪的是,如果我构建游戏,库存从文件中正确加载,如果我尝试保存并退出,游戏会引发错误,但数据仍然正确保存在文件中。我觉得我在这里遗漏了一些非常明显的东西。如果您需要更多信息,请随时询问。
解决方案
推荐阅读
- monolog - 我可以将一个处理器添加到一个 Monolog 处理程序吗?
- css - 如何从应用最后一个类型选择器中排除子级?
- angular - table, thead and tbody component breaks the layout of the table when assemble together
- python - cx_oracle's executemany: order of execution
- javascript - Return back value at input with javascript
- python - 交叉验证:无法使用 clear_session() 清除模型来训练新模型
- mysql - 在 MySQL 中生成一个随机顺序的整数序列
- mysql - 如何在 sql 中使用行号创建视图?SQL
- windows - 在 Edge 中使用 Powershell 激活 Power BI 全屏模式
- robotframework - 对于 Chrome,我想使用套件设置和套件拆解,对于 IE 浏览器,我想使用测试设置和测试拆解