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

本文关键字:文件 拒绝 移动 访问 | 更新日期: 2024-10-25 16:42:37

我正在尝试将文件从 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;
        }