移动文件时文件访问被拒绝

File access denied while moving file

我正在尝试将文件从 a 移动到 b,但我收到 IOException 信息:访问被拒绝。

我很确定这是因为文件仍处于打开状态。我的问题是 - 如何检查文件是否正在使用,以及是否正在等待直到它关闭。

下面示例中的 MoveTo() 调用抛出异常。

public void CreateCheckedStructure() { 

    List<string> checkedDirNew = RemoveTempFolders(GetAllFromDir(Settings.Default.NewFolder));
    List<string> checkedDirCurrent = RemoveTempFolders(GetAllFromDir(Settings.Default.CurrentFolder));

    if (checkedDirNew.Count != 0 && checkedDirCurrent.Count != 0) {
        MyLog.WriteToLog("Moving Checked Files", MyLog.Messages.Info);
        foreach (string checkedNew in checkedDirNew) {
            DirectoryInfo dirInfoNew = new DirectoryInfo(checkedNew);
            foreach (string checkedCurrent in checkedDirCurrent) {
                DirectoryInfo dirInfoCurrent = new DirectoryInfo(checkedCurrent);
                if (dirInfoNew.Name.Equals(dirInfoCurrent.Name)) {
                    string checkedFoldersPath = Settings.Default.CheckedTables + "\" + dirInfoCurrent.Name + "_" + DateTime.Now.ToString("hh-mm-ss");
                    Directory.CreateDirectory(checkedFoldersPath);
                    Directory.CreateDirectory(checkedFoldersPath + "\New");
                    Directory.CreateDirectory(checkedFoldersPath + "\Current");
                    dirInfoCurrent.MoveTo(checkedFoldersPath + "\Current\" + dirInfoNew.Name);
                    dirInfoNew.MoveTo(checkedFoldersPath + "\New\" + dirInfoCurrent.Name);
                    break;
                }
            }
        }
        MyLog.WriteToLog("All Checked Files have been moved", MyLog.Messages.Info);
    } else { MyLog.WriteToLog("No Temporary Folder for Zips found",MyLog.Messages.Warning); }
}

你可以试试我写的这个扩展方法来解决类似的问题

public static async Task<bool> TryToAsync( Action action, int timeoutInSeconds )
        {
            var timeout = DateTime.Now.AddSeconds( timeoutInSeconds );
            while ( DateTime.Now < timeout )
            {
                try
                {
                    action();
                    return true;
                }
                catch ( Exception )
                {
                    await Task.Delay( 200 );
                }
            }

            return false;
        }