c# - 尝试移动文件时收到 UnauthorizedAccessException

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

异常(exception)没有给我任何真实信息,我得到的只是: UnauthorizedAccessException 被捕获 访问该路径被拒绝

最佳答案

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

尝试将代码更改为:

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

关于c# - 尝试移动文件时收到 UnauthorizedAccessException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18109446/

相关文章:

c# - 如何确定 Console.Out 是否已重定向到文件?

c# - 为什么对 Azure 表存储使用异步方法?

asp.net - 尝试使用 VS 2012 打开我的 asp.net 4.5 MVC Web 应用程序时出错。Asp.net 尚未在服务器上注册

sql-server - 如何从 Visual Studio 2012 连接到 SQL Server 2000 数据库

c# - 为什么访问路径被拒绝?

c# - Automapper基类映射

c++ - 无法让简单的 ifstream 在 Visual Studio Express 中工作

c# - 拒绝访问 C# 中的文件

.net - Directory.EnumerateFiles => UnauthorizedAccessException

c# - 为什么我们需要静态构造函数?