I'm writing regression tests and need to manually move a file from one location to another. Each time an UnauthorizedAccessException happens, which I'm assuming has something to do with the permissions of the folder the file has to be moved from? I've checked the file attributes and it is not set to read-only. From other questions and answers, I've tried setting the attribute within the program to Normal. I've also thought maybe using SetAccessControl would help, but I'm having trouble figuring out how to set the FileSecurity parameter. Of course, I could be way off on the issue as well. In terms of permissions, I am an administrator on my local machine and on the network, and if I try moving files to and from the locations in question from powershell, I get no issues, I don't even have to elevate or force, so is Visual Studio running on different permissions, and if so, how can I change that? Here is the code:

    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
            }
        }

The exception isn't giving me any real information, all I'm getting is: UnauthorizedAccessException was caught Acces to the path is denied

有帮助吗?

解决方案

It would appear that you aren't specifying the name of the file when you are doing the move.

try changing the code to this:

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;
            }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top