Home > other >  FIle.Copy() ouput An unhandled exception of type 'System.UnauthorizedAccessException' occu
FIle.Copy() ouput An unhandled exception of type 'System.UnauthorizedAccessException' occu

Time:01-20

I'm trying to use Copy method in File class but I can't get it works it print always the same exception , I have tried to create the folder in Desktop and I'm trying to uncheck the read only attribute in folder but no chance to do this because after saving the property , the folder still always with read only property .

This is my code :

 mypath = "D:\\Test\\image1.png";
 folder = "C:\\Users\\user1\\Desktop\\folder"
 DirectoryInfo directory = Directory.CreateDirectory(folder);
 File.Copy(directory.FullName, mypath);

I've searched on the community for a solution but any of theses solution works for me :

  • enter image description here

    How can I fix this issue?

    CodePudding user response:

    Copy method can't be used with folder name arguments, and also your argument order is wrong.

    Definition of the method is

    public static void Copy (string sourceFileName, string destFileName);
    

    both arguments should be filenames, not directories.

    So you can use

    File.Copy(mypath, folder "\\"   Path.GetFileName(mypath));
    

    CodePudding user response:

    You're trying to copy a directory using File.Copy(sourceFilename,destFilename). On top of that, the destination can't be a directory path

    destFileName String

    The name of the destination file. This cannot be a directory or an existing file.

    To copy a file into a new directory you need to construct the new full file path and reverse the order of the arguments:

    Directory.CreateDirectory(folder);
    
    ...
    
    var fileName=Path.GetFileName(myPath);
    var destPath=Path.Combine(folder,fileName)
    
    File.Copy(myPath,destPath);
    
  •  Tags:  
  • Related