MaxPowerMan2017 MaxPowerMan2017 - 3 years ago 224
C# Question

Unity3d Writing to file path on mac access denied

I try to save a test1.csv to a folder path and Unity says access denied:

How can I give permissions on Mac OS Sierra? I already did CMD+I and gave "everyone" read+write for file and folder but it did not help.. google not helping me out either.

How can I allow permissions? Thank you in advance!

TextWriter tw1 = new StreamWriter ("/Users/X/testunity/test1.csv, true);
tw1.WriteLine ("testfile");
tw1.Close ();


UnauthorizedAccessException: Access to the path '/Users/X/testunity/' is denied.
System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/FileStream.cs:259)
System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share)
(wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)
System.IO.StreamWriter..ctor (System.String path, Boolean append, System.Text.Encoding encoding, Int32 bufferSize) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/StreamWriter.cs:124)
System.IO.StreamWriter..ctor (System.String path, Boolean append)
(wrapper remoting-invoke-with-check) System.IO.StreamWriter:.ctor (string,bool)
LoggerM.LateUpdate () (at Assets/Scripts/LoggerM.cs:137)

Answer Source

Always write to the Application.persistentDataPath+folder path in Unity. This will guarantee that the code will be compatible with most of the platforms Unity supports.

string path = Path.Combine(Application.persistentDataPath, "data");
path = Path.Combine(path, "test1.csv");

//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
    Directory.CreateDirectory(Path.GetDirectoryName(path));
}

using (StreamWriter writer = new StreamWriter(path))
{
    writer.WriteLine("testfile");
}

Personally, File.WriteAllBytes to write to a file so I would recommed that unless you want to write to the file line by line.

string path = Path.Combine(Application.persistentDataPath, "data");
path = Path.Combine(path, "test1.csv");

//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
    Directory.CreateDirectory(Path.GetDirectoryName(path));
}

byte[] data = Encoding.ASCII.GetBytes("testfile");
File.WriteAllBytes(path, data);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download