The question is answered, right answer was accepted
Unable to Copy files from one directory to another.
I'm using the following code to copy a folder and the subfolders within to another location:
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class MainScript : MonoBehaviour {
public void Save () {
modFolder = System.Environment.GetFolderPath (System.Environment.SpecialFolder.MyDocuments) + "/Mods";
modFolder = modFolder.Replace(@"/", @"\");
string dataL = "/Data";
dataL = dataL.Replace(@"/", @"\");
string path1 = directory + dataL;
string path2 = Application.streamingAssetsPath + dataL;
string[] directories = Directory.GetDirectories (modFolder + dataL);
string[] files = Directory.GetFiles(modFolder + dataL);
foreach (string folder in directories) {
string[] subfiles = System.IO.Directory.GetFiles(folder);
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
foreach (string subfile in subfiles) {
string fileName = Path.GetFileName (subfile);
string destFile = @"\" + fileName;
string destFile2 = @"\" + fileName;
File.Copy (subfile, destFile, true);
File.Copy (subfile, destFile2, true);
}
}
foreach (string s in files) {
string fileName = Path.GetFileName (s);
string destFile = Path.Combine (path1, fileName);
string destFile2 = Path.Combine (path2, fileName);
if (!Directory.Exists(path1))
{
Directory.CreateDirectory(path1);
}
if (!Directory.Exists(path2))
{
Directory.CreateDirectory(path2);
}
File.Copy(s, destFile, true);
File.Copy(s, destFile2, true);
}
}
}
The problem is that when I press the save button, Unity gives me the error: UnauthorizedAccessExeption: Access to path "C:\Users\Mike\Documents\Mods\Data\Test\Test.txt" or "\Test.txt" is denied. System.IO.File.Copy (System.String sourceFileName, System.String destFileName, Boolean overwrite) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/File.cs:124)
Answer by TheSkidex · Sep 17, 2017 at 10:46 AM
Have you tried launching Unity in administrator mode? If not try building your project and launching it on administrator mode.
It didn't work but I went back and tried rewriting my code it and got it to work. Here's my code:
public void Save () {
modFolder = System.Environment.GetFolderPath (System.Environment.SpecialFolder.$$anonymous$$yDocuments) + "/$$anonymous$$ods";
modFolder = modFolder.Replace(@"/", @"\"); // explorer doesn't like front slashes//
string [] files = Directory.GetFiles ( modFolder + @"\Data", "*.*", SearchOption.AllDirectories);
string tDirectory = directory + @"\Data";
tDirectory = tDirectory.Replace(@"/", @"\");
string sDirectory = modFolder + @"\Data";
for (int x = 0; x < files.Length; x++) {
string destination = tDirectory + files[x].Substring (sDirectory.Length);
if (!Directory.Exists (Path.GetDirectoryName(destination))) {
Directory.CreateDirectory(Path.GetDirectoryName(destination));
}
File.Copy (files[x], destination, true);
}
}