c# - 尝试复制另一个进程拥有的文件会导致 DirectoryNotFoundException 吗?

标签 c# file exception io

我尝试使用的日志属于另一个与我自己的程序同时运行的程序。当我尝试制作副本时,我收到一个 DirectoryNotFoundException,指出“无法找到路径的一部分”。断言确实通过了。异常在 File.Copy(...) 本身抛出。有了 if(File.Exists(...)) ,程序显然能够在尝试复制文件之前看到它。

编辑:权限可能是一个可能的原因吗?该目录位于C盘根目录下。

编辑:通过添加 Jim Mischel 建议的两个断言并在新的一天的冷光下逐步执行,newControlProgramLog 路径被揭示为罪魁祸首。 GetSaveFilePath() 正在返回我正在测试的特定运行状态的默认路径。我声明了默认值,但从未检查过它是否存在于程序启动时。如果该目录不存在,现在会创建该目录,并且该功能现在可以按预期工作。

向 Christian Hagelid 大喊大叫,因为他从一开始就认为这不是 controlProgramLogPath 的问题。

    private void CopyLogsToDataDirectoy()
    {
        Debug.Assert(Directory.Exists(_controlProgramDirectory));

        string controlProgramLogPath = Path.Combine(_controlProgramDirectory, _controlProgramLogFileName);

        if (File.Exists(controlProgramLogPath))
        {
            string dataFilePath = GetSaveFilePath();
            string newControlProgramLogName = Path.GetFileNameWithoutExtension(dataFilePath);
            newControlProgramLogName = newControlProgramLogName + ".control.log";

            string newControlProgramLogPath = Path.GetDirectoryName(dataFilePath);
            newControlProgramLogPath = Path.Combine(newControlProgramLogPath, newControlProgramLogName);

            File.Copy(controlProgramLogPath, newControlProgramLogPath);
        }
    }

最佳答案

DirectoryNotFoundException 当您指定的部分路径不存在时发生。它不会发生,因为文件被锁定。如果您得到 DirectoryNotFoundException,那么几乎可以肯定是因为您提供的字符串没有引用有效的目录路径。 Documentation还说如果您的代码没有 PathDiscovery 权限,您可以获得此异常。我怀疑你的情况不太可能。

在调用 File.Copy 之前,您应该立即检查 controlProgramLogPathnewControlProgramLogPath 中的路径。

Debug.Assert(Directory.Exists(Path.GetDirectoryName(controlProgramLogPath));
Debug.Assert(Directory.Exists(Path.GetDirectoryName(newControlProgramLogPath));

我怀疑这会揭示问题。

关于c# - 尝试复制另一个进程拥有的文件会导致 DirectoryNotFoundException 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31955330/

相关文章:

java - 在 VSCode 中使用 Formatter 写入文件

c# - 可访问性不一致 : return type is less accessible than method C#

c# - 如何使用SvcUtil生成wsdl?

file - 使用 tcl 从文件中获取变量的值

exception - 派生自异常类警告 : CA2237: Mark ISerializable types with SerializableAttribute

java - jython 2.7.0 中的 SSLHandshakeException

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

c# - 是否可以从Docker容器内部访问任务定义

c# - 从 Microsoft Band 获取心率

c - 从文件 C 中的单行读取多个变量类型