I am trying to copy a file from a remote computer in my AppData folder to then access this file whenever i want. The copy works just fine when the destination path is GetCurrentDir(), but i got an exception every time i try to write elsewhere, in particular AppData.
pathToCopy = Path.Combine(Path.GetTempPath(), "imgTemp.jpg");//doesn't work
pathToCopy = Path.Combine(Directory.GetCurrentDirectory(), "imgTemp.jpg"); //works
And this is the code for my copy :
private void SaveImgTemp(string dest)
{
try
{
File.Copy(dest, pathToCopy, true);
if (File.Exists(pathToCopy))
{
Console.WriteLine("File copied successfully.");
}
}
catch (IOException e)
{
Console.WriteLine("An error occured: " e.Message);
}
}
If anyone has an answer...
CodePudding user response:
You simply don't have write permissions to the app data folder. If you are debugging, you may need to run Visual Studio as administrator. Alternatively you can give read/write access to the AppData folder to your user.
CodePudding user response:
Try using Environment.GetFolderPath()
to make your file names.
Source Path
var sourcePath = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Source Directory",
"image.png");
Where:
Destination Directory
var appData = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
Assembly.GetEntryAssembly().GetName().Name,
"Destination Directory");
// Ensure create directory (doesn't disturb existing)
Directory.CreateDirectory(appData);
Destination File Path
var destPath = Path.Combine(appData, "image.png");
// Overwrite any existing file by that name.
File.Copy(sourcePath, destPath, overwrite: true);
if(File.Exists(destPath))
{
Console.WriteLine($"Successsful write: {destPath}");
}