Quick answer: The operating system refused to let the game create, overwrite or delete the file at that path. In Unity the path is nearly always the problem: it points into the install folder (Application.dataPath, next to the executable, StreamingAssets), it names a folder where a file was meant, or it sits in a location the OS protects. Build save paths from Application.persistentDataPath, create the parent folder before writing, and catch the exception so the player sees a message when a save fails.
Saving works on your machine, and then a player sends a log with UnauthorizedAccessException: Access to the path ... is denied. Your build sat in a folder you own. Theirs is installed somewhere a normal user account cannot write. The exception prints the full path, and that path tells you which of a handful of causes you have. This guide lists them per platform, gives the table of where Application.persistentDataPath points on each one, and shows the code for writing saves in a way that works on all of them.
- The exact error
- What causes it
- Where Application.persistentDataPath points
- How to find which cause is yours
- Fix 1: write to persistentDataPath, and create the folder first
- Fix 2: folders, attributes and locked files
- Fix 3: platform-specific cases
- Fix 4: catch the failure and tell the player
- How to confirm the fix
- Seeing failed saves in Bugnet
- Related guides
- Frequently asked questions
The exact error
UnauthorizedAccessException: Access to the path "C:\Program Files\MyGame\MyGame_Data\save.json" is denied.
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 <...>:0)
System.IO.File.WriteAllText (System.String path, System.String contents) (at <...>:0)
SaveSystem.Save () (at Assets/Scripts/SaveSystem.cs:24)
Several System.IO frames between the first two lines are trimmed here, and <...> stands for a hex id that Unity prints. The frame to act on is the first one in Assets/. The quoting around the path varies: double quotes in most cases, single quotes when the path turns out to be an existing folder, and occasionally no path at all (Access to the path is denied.).
Other file errors look similar in a log and have different fixes:
| Message | Meaning |
|---|---|
UnauthorizedAccessException: Access to the path "X" is denied. | The OS will not allow this operation on this path. This guide. |
IOException: Sharing violation on path X | The file is open elsewhere: another program, or a FileStream of your own that was never closed |
DirectoryNotFoundException: Could not find a part of the path "X". | A folder in the path does not exist yet |
FileNotFoundException: Could not find file "X" | You tried to read a file that is not there |
IOException: Disk full. Path X | No space left on the drive |
What causes it
- Writing into the install folder.
Application.dataPathis theMyGame_Datafolder beside the executable. UnderC:\Program Filesa normal user account cannot write there. It works during development because your build sits on the Desktop or in a project folder that you own. The same applies to a path built from the executable’s location. - A relative path.
File.WriteAllText("save.json", json)writes to the process’s working directory. That depends on how the game was launched and is often the install folder. - Writing into
StreamingAssets. Unity’s manual states that the location is read-only at runtime. On Android and the Web platform it is not a folder at all: the property returns a URL, and file APIs cannot use it. - Writing inside the app bundle on macOS or iOS. On macOS
Application.dataPathis theContentsfolder inside the.app. The bundle is often not writable for the current user, macOS can run a freshly downloaded app from a read-only location, and changing a signed bundle breaks its signature. On iOS the bundle is always read-only. - The path is a folder.
File.WriteAllText(Application.persistentDataPath, json)forgets the file name. A subtler version:Directory.CreateDirectory(path)called with the full file path creates a folder namedsave.json, and every later write to that path is denied. - The file is read-only or hidden. Overwriting or deleting a file with the read-only attribute throws this exception. On Windows, so does overwriting a hidden file. Files copied out of an archive or placed by a sync tool can arrive that way.
- Windows Controlled folder access. This Windows Security feature is off by default. When a player turns it on, apps that Windows does not already trust are blocked from changing files in Documents, Pictures, Videos, Music and Favorites, including when those folders are redirected into OneDrive. A game that saves to
Documents\My Gamesis a typical casualty. Third-party antivirus products have similar shields. - Shared storage on Android. A path such as
/storage/emulated/0/MyGame/save.jsonis outside the app’s own directories. Under scoped storage, an app that targets Android 11 or later gains no extra access from theWRITE_EXTERNAL_STORAGEpermission, and the write is refused. - The file belongs to another user. On Linux and macOS, running the game once with
sudoleaves its save folder owned by root, and normal runs can no longer write to it.
Where Application.persistentDataPath points
Application.persistentDataPath is the folder Unity sets aside for data that must survive between runs. The current user can write to it on every platform that supports it, and no permission prompt is needed.
| Platform | Location (from Unity’s scripting reference) |
|---|---|
| Windows | %userprofile%\AppData\LocalLow\<companyname>\<productname> |
| macOS | ~/Library/Application Support/<company name>/<product name>. For players the reference also lists ~/Library/Application Support/unity.<company name>.<product name>. |
| Linux | $XDG_CONFIG_HOME/unity3d/<company name>/<product name>, where $XDG_CONFIG_HOME defaults to ~/.config |
| iOS | /var/mobile/Containers/Data/Application/<guid>/Documents |
| Android | /storage/emulated/<userid>/Android/data/<packagename>/files on most devices |
| Web | /idbfs/<hash>, a virtual file system backed by the browser’s IndexedDB |
| tvOS | Not supported. The property returns an empty string. |
The company and product names come from Edit > Project Settings > Player. Changing either one after release changes the folder, and existing players appear to lose their saves. Do not hardcode any row of this table. Read the property at runtime and log it once at startup, so every player log shows where that install keeps its files.
How to find which cause is yours
The path in the message is the evidence. Read it before anything else.
- It contains
Program Files,_Data,.app/ContentsorStreamingAssets: you are writing into the install (causes 1 to 4). Search your scripts forApplication.dataPath,Application.streamingAssetsPathand file calls with a bare file name. - It is wrapped in single quotes, or it ends in a folder name: the path is a directory (cause 5). Open the location in a file browser and look for a folder named like your save file.
- It is under
persistentDataPathand still denied: check the file’s attributes (cause 6) and its owner (cause 9). - It contains
DocumentsorOneDrive, on Windows only, for some players: suspect Controlled folder access (cause 7). The player can confirm it in Windows Security > Virus & threat protection > Ransomware protection, where blocked apps are listed in the protection history. - It starts with
/storage/emulated/0/or/sdcard/and does not containAndroid/data/: shared storage on Android (cause 8).
If you do not have the message, log the path you are about to use:
Debug.Log($"Saving to: {path} (persistentDataPath = {Application.persistentDataPath})");
Fix 1: write to persistentDataPath, and create the folder first
// Broken: inside the install folder
string path = Application.dataPath + "/save.json";
File.WriteAllText(path, json);
// Fixed
string dir = Path.Combine(Application.persistentDataPath, "Saves");
Directory.CreateDirectory(dir); // does nothing if it already exists
string path = Path.Combine(dir, "slot1.json");
File.WriteAllText(path, json);
Use Path.Combine for every join. String concatenation without a separator produces a sibling path such as ...\MyGamesave.json, outside the folder you meant.
If a released version already wrote saves into the install folder, some players have files there (the ones whose install location happened to be writable). Reading from the install folder is allowed, so copy the old file across on first run:
string oldPath = Path.Combine(Application.dataPath, "save.json");
if (!File.Exists(path) && File.Exists(oldPath))
File.Copy(oldPath, path);
Telling players to “run as administrator” makes the error go away and is not a fix. The saves still sit in a folder that updates and uninstalls can wipe. How to Fix Games That Can’t Save: Permission Denied Writing to the Install Folder covers the migration in more detail.
Fix 2: folders, attributes and locked files
// Broken: creates a FOLDER named slot1.json, then the write is denied
Directory.CreateDirectory(path);
File.WriteAllText(path, json);
// Fixed: create the parent folder
Directory.CreateDirectory(Path.GetDirectoryName(path));
File.WriteAllText(path, json);
Fixing the code does not remove the folder that the broken version already created on players’ machines, so the fixed build keeps failing for them. Clean it up once:
if (Directory.Exists(path)) // a folder is sitting where the file should be
Directory.Delete(path, true);
For a read-only file, clear the attribute before overwriting or deleting:
if (File.Exists(path))
{
FileAttributes attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.ReadOnly) != 0)
File.SetAttributes(path, attributes & ~FileAttributes.ReadOnly);
}
A file that is open in another program gives IOException: Sharing violation, not this exception. When the other program is your own code, the cure is a using block around every FileStream, StreamWriter and StreamReader so the handle is released before the next save.
Fix 3: platform-specific cases
Files you ship and then need to change
Default settings, level files or a starter database belong in StreamingAssets as read-only originals. On first run, copy them into persistentDataPath and work on the copy. On desktop platforms File.Copy does that. On Android and the Web platform the source is a URL, so load it with UnityWebRequest and write the downloaded bytes to the new location. Fix: Unity StreamingAssets Not Loading on Android shows the loading side.
Android
Keep saves in Application.persistentDataPath. It is the app’s own directory, it needs no storage permission, and Android removes it when the app is uninstalled. Do not build paths from /sdcard or /storage/emulated/0. Adding WRITE_EXTERNAL_STORAGE to the manifest does not bring back access to shared storage for apps that target current Android versions.
Windows Controlled folder access and antivirus
AppData\LocalLow is not on the default list of protected folders, so a game that saves to persistentDataPath is normally unaffected. If you save to Documents on purpose, for example so players can find screenshots, expect some players to be blocked. Catch the failure, tell them the write was blocked, and point them to Allow an app through Controlled folder access in the Ransomware protection settings. Your game cannot switch the protection off, and should not try.
Web
A Web build has no disk. persistentDataPath maps to browser storage, and the usual failure is data that does not persist, not an access error. See Fix: Unity WebGL PlayerPrefs or IndexedDB Not Persisting Between Sessions.
Fix 4: catch the failure and tell the player
Even with the right path, a write can be refused by security software or a damaged user profile. An unhandled exception in a save call means the player keeps playing with no idea that nothing is being saved. Return a result and show it:
using System;
using System.IO;
using UnityEngine;
public static class SaveWriter
{
public static bool TrySave(string path, string json, out string playerMessage)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
File.WriteAllText(path, json);
playerMessage = null;
return true;
}
catch (UnauthorizedAccessException e)
{
playerMessage = "The game was not allowed to write your save file. " +
"Check antivirus or folder protection settings.";
Debug.LogError("Save failed: access denied\n" + e.Message);
}
catch (IOException e)
{
playerMessage = "Your save file could not be written. " +
"Check free disk space and close other programs that may be using it.";
Debug.LogError("Save failed: I/O error\n" + e.Message);
}
return false;
}
}
Show playerMessage in the game’s UI and keep the unsaved state in memory so the player can try again. The log call puts a fixed sentence on the first line and the exception text, which contains the path, on the second. The reason for that split is in the Bugnet section below. To make the write itself safe against crashes, combine this with the temporary-file pattern in How to Fix “ArgumentException: JSON parse error” From JsonUtility in Unity.
How to confirm the fix
Test from a location you do not own. On Windows, copy the build into C:\Program Files, start it normally (not as administrator), save, quit and load. Check that the file appears under AppData\LocalLow and that nothing new appears in the install folder. Then mark the save file read-only in its Properties dialog and save again. Turn on Controlled folder access and repeat if your game writes to Documents. On Android, install the build on a device and save and reload with no storage permission granted. In every case the game either saves or shows your message, and Player.log or logcat contains no unhandled UnauthorizedAccessException.
Seeing failed saves in Bugnet
The Bugnet Unity SDK files unhandled exceptions and Debug.LogError calls with the stack trace, recent log lines, game version, platform and OS version, so a failed save on a player’s machine reaches you without the player having to describe it. The platform and OS fields quickly show whether a problem is limited to Windows or to one Android version.
One property of this exception works against you. Its message contains the full path, and on desktop the path contains the player’s user name. A report’s title is the first line of the logged message, and reports stack by title, so the raw exception from a hundred players becomes a hundred separate entries. The TrySave method above logs a fixed first line (“Save failed: access denied”) and puts the path on the second, which gives you one entry with an occurrence count and the path in each report’s body. Bugnet cannot see folder permissions, antivirus settings or what blocked the write. The path and the OS version are the clues it gives you. What a report contains is described in the bug reports guide.
Related guides
- How to Fix Games That Can’t Save: Permission Denied Writing to the Install Folder
- How to Fix Save and Asset Failures for Players With Non-ASCII Windows Usernames
- How to Fix “ArgumentException: JSON parse error” From JsonUtility in Unity
- How to Fix Saves Silently Failing When the Player’s Disk Is Full
- How to Improve Your Game’s Save Reliability
Frequently asked questions
What does “UnauthorizedAccessException: Access to the path is denied” mean in Unity?
The operating system refused to let the game create, overwrite or delete the file at the path shown in the message. In Unity projects the path usually points into the install folder, names a folder where a file was meant, or sits in a protected location. Writing to Application.persistentDataPath avoids most cases.
Why does saving work in the editor but fail in the installed game?
During development the build sits in a folder your account owns, so writing next to the executable or into Application.dataPath succeeds. Installed under Program Files, or inside an app bundle on macOS and iOS, that same location is not writable for a normal user.
Where should a Unity game save files?
In Application.persistentDataPath, joined to your file name with Path.Combine. On Windows that is under AppData\LocalLow with your company and product name, and each other platform has its own equivalent. Create the folder with Directory.CreateDirectory before the first write.
Can I write to StreamingAssets or Application.dataPath at runtime?
No. Unity documents StreamingAssets as read-only at runtime, and on Android and the Web platform it is a URL that file APIs cannot use. Application.dataPath is the install folder. Copy any file you need to change into Application.persistentDataPath on first run and edit the copy.
What is the difference between access denied and a sharing violation?
Access denied, UnauthorizedAccessException, means the OS does not permit the operation on that path at all. IOException with the text Sharing violation on path means the file is open somewhere else, often in a stream your own code did not close. The second is fixed with using blocks, not with a different folder.
The exception prints the full path, and the path is the diagnosis. If it is not under Application.persistentDataPath, move the file there before looking for any other cause.