Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# UnauthorizedAccessException in File.Copy

Tags:

c#

I am brushing up on my C# so I decided to write a program that I can use to easily import photos that I take. A little background...I shoot photos in JPEG and RAW and then go through and pick through the JPEGs since they are smaller and easier to handle/preview. I then import only those RAW files that are worth messing with in post production.

I wanted to write a simple program to copy the RAW files from one directory that match the JPEGs that I've sifted through in another.

Here is the code:

static void Main(string[] args)
    {
        Console.WriteLine("Enter the JPEG Origin Directory: "); 
        string originDirectory = @"C:\Users\Greg\Pictures\Summer 2013\Back Bay\testJPEG";

        Console.WriteLine("Enter the RAW Origin Directory: ");
        string copyDirectory = @"C:\Users\Greg\Pictures\Summer 2013\Back Bay\testRAW";

        Console.WriteLine("Enter the RAW Import Directory: ");
        string rawCopyDirectory = @"C:\Users\Greg\Pictures\Summer 2013\Back Bay\testRAWImport"; 

        char[] delimiterChars = { '_', '.' };

        List<string> filesToCopy = new List<string>();
        List<string> CopiedFiles = new List<string>(); 

        foreach (var filePath in Directory.GetFiles(originDirectory))
        {
            Console.WriteLine("Filepath: '{0}'", filePath);
            string[] words = filePath.Split(delimiterChars);

            filesToCopy.Add(words[1]); 
        }

        filesToCopy.ForEach(Console.WriteLine);

        foreach (var copyFilePath in Directory.GetFiles(copyDirectory))
        {
          string[] delimited = copyFilePath.Split(delimiterChars);     

          if (filesToCopy.Contains(delimited[1]))
          {
              Console.WriteLine("Copied: '{0}'", copyFilePath);

              string fileName = Path.GetFileName(copyFilePath);

              string sourcePath = Path.GetDirectoryName(copyFilePath);

              string targetPath = rawCopyDirectory;

              string sourceFile = System.IO.Path.Combine(sourcePath, fileName);

              string destFile = System.IO.Path.Combine(targetPath, fileName);


             System.IO.File.Copy(sourcePath, destFile, true); 

          }


        }

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();

    }

Everything seems to be working as I'd expect when I write all the variables to the console, however I'm getting an exception on Copy.File that indicates the files are read only. I checked, and they aren't, however the folder itself is, and despite my best efforts I cannot unflag my test folders as readonly. Any help would be appreciated, I've pasted the exception log below.

System.UnauthorizedAccessException was unhandled
  HResult=-2147024891
  Message=Access to the path 'C:\Users\Greg\Pictures\Summer 2013\Back Bay\testRAW' is denied.
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
       at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)
       at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Greg\documents\visual studio 2010\Projects\Photo Importer\Photo Importer\photoImporter.cs:line 56
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at System.Activator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
like image 556
user2736424 Avatar asked Sep 01 '13 00:09

user2736424


People also ask

What is C in simple words?

C Introduction C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C or C++ same?

While C and C++ may sound similar, their features and usage differ. C is a procedural programming language that support objects and classes. On the other hand C++ is an enhanced version of C programming with object-oriented programming support.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.

What is C language used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


2 Answers

The problem can be that you can not delete or overwrite read-only files. The solution is to change the attributes.

if(File.Exists(destFile))
{
    File.SetAttributes(destFile, FileAttributes.Normal);
}
File.Copy(sourcePath, destFile, true); 
like image 86
Dmitrii Dovgopolyi Avatar answered Oct 27 '22 13:10

Dmitrii Dovgopolyi


You are trying to access a file outside of what your program can use.

Try looking at this older post Why is access to the path denied?

like image 23
ismellike Avatar answered Oct 27 '22 14:10

ismellike