【问题标题】:Receiving UnauthorizedAccessException When Trying to Move File尝试移动文件时收到 UnauthorizedAccessException
【发布时间】:2013-08-09 04:29:42
【问题描述】:

我正在编写回归测试,需要手动将文件从一个位置移动到另一个位置。每次发生 UnauthorizedAccessException 时,我假设这与必须从中移动文件的文件夹的权限有关?我检查了文件属性,它没有设置为只读。从其他问题和答案中,我尝试过 将程序中的属性设置为正常。我还认为使用 SetAccessControl 可能会有所帮助,但我无法弄清楚如何设置 FileSecurity 参数。当然,我也可能在这个问题上有所偏离。 在权限方面,我是本地计算机和网络上的管理员,如果我尝试从 powershell 将文件移入和移出相关位置,我不会遇到任何问题,我什至不必提升或强制, Visual Studio 是否以不同的权限运行,如果是,我该如何更改? 代码如下:

    internal static bool Process5010Claims(string batch)
    {
        string batchRegex = createBatchRegex(batch);
        string batchOnFileSystem = addDecimalToBatch(batch);
        bool isFound = false;
        string pth = @"\\hedgefrog\root\uploads";
        string destination = @"\\apexdata\data\claimstaker\claims\auto\5010";
        string[] files = Directory.GetFiles(pth);
        foreach (var file in files)
        {
            if (Regex.IsMatch(file, batchRegex))
            {
                string fullPath = Path.Combine(pth, batchOnFileSystem);
                var attr = new FileInfo(fullPath);


                //
                try
                {
                    File.Move(fullPath, destination);
                    isFound = true;
                    break;
                }
                catch (FileNotFoundException)
                {//Already been moved to the new directory
                }
                catch (UnauthorizedAccessException e)
                {
                    //In the middle of being moved?
                }
                catch (IOException)
                {
                }//Already been moved to the new directory
            }
        }

这个例外没有给我任何真实的信息,我得到的只是: UnauthorizedAccessException 被捕获 访问路径被拒绝

【问题讨论】:

    标签: c# visual-studio-2012 unauthorizedaccessexcepti


    【解决方案1】:

    您在移动时似乎没有指定文件的名称。

    尝试将代码更改为:

    if (Regex.IsMatch(file, batchRegex))
            {
                var fullPath = Path.Combine(pth, batchOnFileSystem);
                var fullDestinationPath = Path.Combine(destination, batchOnFileSystem);
                var attr = new FileInfo(fullPath);
                try
                {
                    File.Move(fullPath, fullDestinationPath);
                    isFound = true;
                    break;
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      相关资源
      最近更新 更多