File.Copy 中的 C# UnauthorizedAccessException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18554108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:34:53  来源:igfitidea点击:

C# UnauthorizedAccessException in File.Copy

c#

提问by user2736424

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.

我正在复习我的 C#,所以我决定编写一个程序,我可以用它来轻松导入我拍摄的照片。一点背景……我用 JPEG 和 RAW 拍摄照片,然后通过 JPEG 进行挑选,因为它们更小且更易于处理/预览。然后我只导入那些值得在后期制作中处理的 RAW 文件。

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.

我想编写一个简单的程序来从一个目录中复制与我在另一个目录中筛选过的 JPEG 相匹配的 RAW 文件。

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.Filethat 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.

当我将所有变量写入控制台时,一切似乎都在按我的预期工作,但是我收到一个异常Copy.File,表明文件是只读的。我检查过,但它们不是,但是文件夹本身是,尽管我尽了最大努力,但我无法将我的测试文件夹取消标记为只读。任何帮助将不胜感激,我已经粘贴了下面的异常日志。

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: 

采纳答案by ismellike

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?

尝试查看这篇较旧的帖子为什么访问路径被拒绝?

回答by Dmitry Dovgopoly

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); 

回答by user2736424

Turns out I was calling the wrong variable in File.Copy, and instead was trying to copy a path instead of a file (derp). Everything works now! Thanks for the replies!

结果我在 File.Copy 中调用了错误的变量,而是试图复制路径而不是文件 (derp)。现在一切正常!感谢您的回复!