移动文件

时间:2016-04-20 15:34:01

标签: c# file-handling access-denied

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

1 个答案:

答案 0 :(得分:0)

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

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