尝试移动文件时接收UnauthorizedAccessException

时间:2013-08-07 17:04:36

标签: c# visual-studio-2012 unauthorizedaccessexcepti

我正在编写回归测试,需要手动将文件从一个位置移动到另一个位置。每次发生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 该路径的访问被拒绝

1 个答案:

答案 0 :(得分:2)

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

尝试将代码更改为:

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;
            }
相关问题