public async Task <object> Move(Guid id, Guid newParentId, string options) { try { Log("id: " + id + " newParentId: " + newParentId + " options: " + options); var item = await FileSystem.GetItemAsync(id).ConfigureAwait(false); if (item == null) { LogWarning("Item " + id + " was not found."); return(Json(null)); } var moveOptions = new MoveOptions(); if (options != null && options.IndexOf("copy:true", StringComparison.OrdinalIgnoreCase) >= 0) { moveOptions.Copy = true; } return(await item.MoveToAsync(newParentId, moveOptions).ConfigureAwait(false)); } catch (UnauthorizedAccessException) { return(Unauthorized()); } }
/// <summary> /// Automatically moves a checker from and to the specified points. /// </summary> /// <param name="startPoint"></param> /// <param name="endPoint"></param> private MoveResult MoveChecker(Point startPoint, Point endPoint) { BGMove move = MoveOptions.GetMove(startPoint.ID, endPoint.ID); if (move != null && DiceRoll.Use(move)) { if (move.IsHit) { JailChecker(endPoint.PickUp()); } endPoint.GetCheckerFrom(startPoint); m_MovesMade.Push(move); MoveOptions = new BGMoveOptions(CurrentPlayer.ID, Board.GetBoardMap(), DiceRoll); EventHelper.Raise(this, MoveOptionsUpdated); EventHelper.Raise(this, CheckerMoved); if (CheckForWin(CurrentPlayer)) { return(CurrentPlayer.ID == BGPlayerID.Player1 ? MoveResult.Player1Win : MoveResult.Player2Win); } else { return(MoveResult.Success); } } else { return(MoveResult.Invalid); } }
public static void Run() { var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); var apiInstance = new PagesApi(configuration); try { var fileInfo = new FileInfo { FilePath = "WordProcessing/four-pages.docx" }; var options = new MoveOptions { FileInfo = fileInfo, OutputPath = "Output/move-pages.docx", PageNumber = 1, NewPageNumber = 2 }; var request = new MoveRequest(options); var response = apiInstance.Move(request); Console.WriteLine("Output file path: " + response.Path); } catch (Exception e) { Console.WriteLine("Exception while calling api: " + e.Message); } }
/// <summary> /// Saving user statistics both in the storage and in the json file database /// if user is identified by his/her authorization <paramref name="token"/>. /// </summary> /// <param name="token">User's authorization token.</param> /// <param name="outcome">Game outcome. One of <see cref="GameOutcome"/></param> /// <param name="move">Chosen move option. One of <see cref="MoveOptions"/></param> /// <returns>Returns true if user was found by token, else returns false.</returns> public async Task <bool> SaveAsync(string token, GameOutcome outcome, MoveOptions move) { // get user id var userWithToken = (await _tokens.GetAllAsync()).Where(tk => tk.Item == token).FirstOrDefault(); // if user was not found if (userWithToken == null) { // only one logger message here so as not to litter the file with messages // about saving statistics, since this method will be called very often _logger.LogInformation($"{nameof(StatisticsService)}: User was not identified for saving statistics. The authorization token did not exist or expired."); return(false); } // get user id var userId = userWithToken.Id; // add user statistics to the storage if it doesn't exist await _statistics.AddAsync(new UserStatistics(userId), userId, new StatisticsEqualityComparer()); // change state var record = await _statistics.GetAsync(userId); record.AddRoundInfo(DateTime.Now, outcome, move); // map with StatisticsDb var statisticsToSave = ModelsMapper.ToStatisticsDb(record); //save to file await _jsonDataService.WriteAsync(_options.StatisticsPath + $"{userId}.json", statisticsToSave); return(true); }
/// <summary> /// Updates the user interaction with the checkers. /// </summary> private void UpdateCheckerSelection() { if (IsLocked) { return; } if (SelectedChecker == null) { if (Input.GetMouseButtonDown(0) && MoveOptions.CanMove()) { SelectChecker(); } else if (Input.GetMouseButtonDown(1)) { Undo(); } } else { if (Input.GetMouseButtonDown(0)) { DropChecker(); } else if (Input.GetMouseButtonDown(1)) { ReturnChecker(); } } }
public FileInfo MoveTo(string destinationPath, MoveOptions moveOptions) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, null, moveOptions, null, null, out destinationPathLp, PathFormat.RelativePath); return(new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath)); }
// Most of these checks are done in the move options check, // but separating them here allows us to have more helpful error messaging public static Rule CheckMove(Move move, Board board, Player player) { if (move.Piece.Color == PlayerColor.None) { return(Rule.NotAPiece); } if (move.Piece.Color != player.Color) { return(Rule.OutOfTurn); } if (move.Delta == Delta.Zero) { return(Rule.Unmoved); } if (!board.InBounds(move.Destination)) { return(Rule.OutOfBounds); } if (move.Piece.Color == board[move.Destination].Color) { return(Rule.SquareOccupied); } return(MoveOptions.GetCheckedMoveOptions(move.Origin, board).Contains(move.Destination) ? Rule.None : Rule.Impossible); }
public FileInfo MoveTo(string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, null, moveOptions, null, null, out destinationPathLp, pathFormat); return(null != destinationPathLp ? new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath) : null); }
public async Task <ActionResult <RoundWithBotResult> > Post([FromHeader(Name = "X-AuthToken"), Required] string userToken, [FromBody] string userFigureRaw, [FromServices] IStorage <string> tokens) { _logger.LogInformation($"{nameof(BotGameController)}: Round with bot requested"); var userId = (await tokens.GetAllAsync()) .Where(tk => tk.Item == userToken) .Select(tk => tk.Id) .FirstOrDefault(); if (userId > 0) //if user was found { bool isCorrectFigure = Enum.TryParse <MoveOptions>(userFigureRaw, true, out MoveOptions userFigure); if (isCorrectFigure == false) { return(BadRequest("Invalid move option")); } MoveOptions botMoveOption = _botGameService.MakeRandomChoice(); GameOutcome roundResult = _gameService.GetGameResult(userFigure, botMoveOption); _logger.LogInformation($"{nameof(BotGameController)}: Round with bot ended"); RoundWithBotResult result = new RoundWithBotResult() { UserMoveOption = userFigure, BotMoveOption = botMoveOption, RoundResult = roundResult.ToString() }; var jsonResult = JsonSerializer.Serialize(result); return(Ok(jsonResult)); } return(StatusCode((int)HttpStatusCode.Forbidden, "Unauthorized access")); }
public DirectoryInfo MoveTo(string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, null, moveOptions, null, null, out destinationPathLp, pathFormat); return(new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath)); }
public DirectoryInfo MoveTo(string destinationPath, MoveOptions moveOptions) { string destinationPathLp; CopyToMoveToInternal(destinationPath, null, moveOptions, null, null, out destinationPathLp, PathFormat.RelativePath); return(new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath)); }
public void HandleNewUnitSelected(UnitModel unit) { UIController.CloseAllUI(); ClearSelectedUnit(); CurrSelectedUnit = unit; if (unit != null) { UIController.OpenUnitUI(unit); moveOptions = MapController.Model.GetHex(unit.CurrentPos).PossibleMoves(unit.MovementCurr, unit.Faction); foreach (HexModel reachableHex in moveOptions.Movable.Keys) { reachableHex.HighlightHex(HexModel.HexHighlightTypes.Move); } foreach (HexModel reachableHex in moveOptions.Attackable.Keys) { reachableHex.HighlightHex(HexModel.HexHighlightTypes.Attack); } foreach (HexModel reachableHex in moveOptions.PotentialAttacks.Keys) { reachableHex.HighlightHex(HexModel.HexHighlightTypes.PotentialAttack); } } }
public DirectoryInfo MoveTo(string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, null, moveOptions, null, null, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return(null != destinationPathLp ? new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath) : null); }
/// <summary> /// Saves information and results of the played game round. /// </summary> /// <param name="date">The date of the played round.</param> /// <param name="outcome">The round outcome. One of <see cref="GameOutcome"/></param> /// <param name="move">Player's move. One of <see cref="MoveOptions"/></param> public void AddRoundInfo(DateTime date, GameOutcome outcome, MoveOptions move) { var stringDate = date.ToString("dd.MM.yyyy"); History.TryAdd(stringDate, new GameOutcomeCounts()); History[stringDate].Increment(outcome); IncrementMoveOptionCount(move); }
public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { string destinationPathLp; CopyMoveResult cmr = CopyToMoveToInternal(destinationPath, null, moveOptions, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath); CopyToMoveToInternalRefresh(destinationPath, destinationPathLp); return(cmr); }
/// <summary> /// Method that handles "move" command. /// </summary> /// <param name="moveOptions">Options passed to the command.</param> internal static void HandleMove(MoveOptions moveOptions) { CommandHandlerHelper.TryExecute(moveOptions, options => { var client = CommandHandlerHelper.CreateClient(options); client.Move(options.CurrentName, options.NewName); }); }
public static void Start(MoveOptions options) { MoveList[options.GameObject] = options; options.OnFinished += (sender, e) => { MoveTo.MoveList.Remove((sender as MoveTo.MoveOptions).GameObject); }; }
public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { string destinationPathLp; CopyMoveResult cmr = CopyToMoveToCore(destinationPath, null, moveOptions, progressHandler, userProgressData, out destinationPathLp, pathFormat); CopyToMoveToCoreRefresh(destinationPath, destinationPathLp); return(cmr); }
public EtlOptions(ArchiveOptions archiveOptions, EncryptionOptions encryptionOptions, LoggingOptions loggingOptions, MoveOptions moveOptions, MoveDbOptions moveDbOptions, WatcherOptions watcherOptions) { ArchiveOptions = archiveOptions; EncryptionOptions = encryptionOptions; LoggingOptions = loggingOptions; MoveOptions = moveOptions; MoveDbOptions = moveDbOptions; WatcherOptions = watcherOptions; }
/// <summary> /// Picks up a checker from the specified point. /// </summary> /// <param name="point"></param> private void PickupChecker(Point point) { Checker checker = point.CurrentChecker; if (checker != null && MoveOptions.CanMoveFrom(point.ID)) { SelectedChecker = point.PickUp(); EventHelper.Raise(this, CheckerPickedUp); } }
/// <summary> /// Executes the move command /// </summary> /// <param name="options">The command options</param> public static void Run(MoveOptions options) { Directory.CreateDirectory(options.TargetDirectory); void Handler(string path) { string filename = Path.GetFileName(path); File.Move(path, Path.Combine(options.TargetDirectory, filename)); } Run(options, Handler); }
private void IncrementMoveOptionCount(MoveOptions move) { switch (move) { case MoveOptions.Rock: RockCount++; break; case MoveOptions.Paper: PaperCount++; break; case MoveOptions.Scissors: ScissorsCount++; break; default: throw new ArgumentOutOfRangeException(nameof(move), "Undefined move option."); } }
public RtdxStarterViewModel(IStarterModel model, ICommonStrings commonStrings) { this.model = model ?? throw new ArgumentNullException(nameof(model)); if (commonStrings == null) { throw new ArgumentNullException(nameof(commonStrings)); } this.PokemonOptions = commonStrings.Pokemon.Select(kv => new ListItem <CreatureIndex>(kv.Value, kv.Key)).OrderBy(li => li.DisplayName).ThenBy(li => li.Value).ToList(); this.MoveOptions = commonStrings.Moves.Select(kv => new ListItem <WazaIndex>(kv.Value, kv.Key)).OrderBy(li => li.DisplayName).ThenBy(li => li.Value).ToList(); this.PokemonOptionsByValue = PokemonOptions.ToDictionary(li => li.Value, li => li); this.MoveOptionsByValue = MoveOptions.ToDictionary(li => li.Value, li => li); }
public async Task <string> PlayRoundWithBot(string playerId, MoveOptions moveOption) { var requestMessage = GetRequestMessage( HttpMethod.Post, "bot/play", playerId, new StringContent(JsonSerializer.Serialize(moveOption.ToString()), Encoding.UTF8, "application/json")); try { var response = await _client.SendAsync(requestMessage); if (response.StatusCode == HttpStatusCode.OK) { var responseMessage = await response.Content.ReadAsStringAsync(); try { var roundResult = JsonSerializer.Deserialize <RoundWithBotResult>(responseMessage); if (roundResult == null) { _logger.LogError($"{nameof(GameService)}: Server returned unexpected response"); throw new ServiceException("Error occured. Try again later"); } return("\nRound summary\n" + $"Your choice: {roundResult.UserMoveOption}\n" + $"Bot's choice: {roundResult.BotMoveOption}\n" + $"Round result: {roundResult.RoundResult}\n"); } catch (Exception exception) { if (exception is ArgumentNullException || exception is JsonException || exception is NotSupportedException) { _logger.LogError($"{nameof(GameService)}: Server returned unexpected response"); throw new ServiceException("Error occured. Try again later"); } throw; } } return("Error occured. Try again later"); } catch (HttpRequestException) { throw new ConnectionException("Unable to connect to the server. Please, try again later"); } }
public GameOutcome GetGameResult(MoveOptions playerChoice, MoveOptions opponentChoice) { MoveOptionsPair figurePair = new MoveOptionsPair(playerChoice, opponentChoice); bool isSuccess = _gameResults.TryGetValue(figurePair, out GameOutcome result); if (isSuccess) { _logger.LogInformation($"{nameof(GameService)}: Game result calculated"); return(result); } _logger.LogError($"{nameof(GameService)}: Invalid pair of figures"); throw new ServiceException("Invalid pair of figures"); }
private void ShowMoves() { var origin = this.rectTransform.offsetMax.ToPosition(this.boardRenderer.Offset); var playerColor = this.boardRenderer.Player; this.originalPosition = Position.Normalize(origin, playerColor); this.possibleMoves = MoveOptions.GetCheckedMoveOptions(this.originalPosition, this.boardRenderer.State.Board); this.boardRenderer.HighlightPossibleMoves(this.possibleMoves); this.statusText.text = string.Join(",", this.possibleMoves); }
public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { // Reject DelayUntilReboot. if ((moveOptions & MoveOptions.DelayUntilReboot) != 0) { throw new ArgumentException("The DelayUntilReboot flag is invalid for this method.", "moveOptions"); } string destinationPathLp; var cmr = CopyToMoveToCore(destinationPath, false, null, moveOptions, progressHandler, userProgressData, out destinationPathLp, pathFormat); UpdateSourcePath(destinationPath, destinationPathLp); return(cmr); }
public async Task <IFileSystemInfo> MoveToAsync(Guid newParentId, MoveOptions options = null) { if (IsRoot) { throw new UnauthorizedAccessException(); } using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { var res = await System.MoveToAsync(this, newParentId, options).ConfigureAwait(false); scope.Complete(); System.SendEvents(); return(res); } }
/// <inheritdoc cref="IMouse.MoveAsync(double, double, MoveOptions)"/> public async Task MoveAsync(double x, double y, MoveOptions options = null) { int steps = options?.Steps ?? 1; double fromX = _x; double fromY = _y; _x = x; _y = y; for (int i = 1; i <= steps; i++) { double middleX = fromX + ((x - fromX) * (i / steps)); double middleY = fromY + ((y - fromY) * (i / steps)); await _raw.MoveAsync(middleX, middleY, _lastButton, _buttons, _keyboard.Modifiers).ConfigureAwait(false); } }
public static void ExecuteAIMove(UnitModel unit) { HexModel hex = MapController.Model.GetHex(unit.CurrentPos); MoveOptions possibleMoves = hex.PossibleMoves(unit.MovementCurr, unit.Faction); SortedDupList <UnitMoves> RankedMoves = new SortedDupList <UnitMoves>(); RankedMoves.Insert(new UnitMoves(hex), hex.DefenseMod); foreach (HexModel potentialMove in possibleMoves.Movable.Keys) { RankedMoves.Insert(new UnitMoves(potentialMove), potentialMove.DefenseMod); } foreach (HexModel potentialAttack in possibleMoves.Attackable.Keys) { UnitModel UnitToAttack = MapController.Model.GetUnit(potentialAttack.Coord); RankedMoves.Insert(new UnitMoves(potentialAttack), hex.DefenseMod + GetAttackGoodness(unit, UnitToAttack)); } foreach (KeyValuePair <HexModel, float> pair in possibleMoves.Movable) { foreach (HexModel attackableNeighbor in pair.Key.Neighbors) { if (pair.Value - attackableNeighbor.MoveDifficulty >= 0 && attackableNeighbor.ContainsEnemy(unit.Faction)) { UnitModel UnitToAttack = MapController.Model.GetUnit(attackableNeighbor.Coord); RankedMoves.Insert(new UnitMoves(pair.Key, attackableNeighbor), pair.Key.DefenseMod + GetAttackGoodness(unit, UnitToAttack)); } } } Debug.Log(unit.UnitName + " ranked moves: "); foreach (KeyValuePair <float, UnitMoves> rankedMove in RankedMoves.GetList()) { string moves = ""; foreach (HexModel move in rankedMove.Value.Moves) { moves = moves + ", " + move.Coord.ToString(); } Debug.Log(rankedMove.Key + ", " + moves); } ExecuteChosenMoves(unit, RankedMoves.TopValue()); }
public static CopyMoveResult Move(string sourceFileName, string destinationFileName, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveInternal(false, null, sourceFileName, destinationFileName, false, null, moveOptions, progressHandler, userProgressData, pathFormat); }
public static void Move(string sourceFileName, string destinationFileName, MoveOptions moveOptions) { CopyMoveInternal(false, null, sourceFileName, destinationFileName, false, null, moveOptions, null, null, PathFormat.RelativePath); }
internal static CopyMoveResult CopyMoveInternal(bool isFolder, KernelTransaction transaction, string sourceFileName, string destinationFileName, bool preserveDates, CopyOptions? copyOptions, MoveOptions? moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { #region Setup if (pathFormat == PathFormat.RelativePath) { Path.CheckValidPath(sourceFileName, true, true); Path.CheckValidPath(destinationFileName, true, true); } else { // MSDN:. NET 3.5+: NotSupportedException: Path contains a colon character (:) that is not part of a drive label ("C:\"). Path.CheckValidPath(sourceFileName, false, false); Path.CheckValidPath(destinationFileName, false, false); } string sourceFileNameLp = Path.GetExtendedLengthPathInternal(transaction, sourceFileName, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator); string destFileNameLp = Path.GetExtendedLengthPathInternal(transaction, destinationFileName, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator); // MSDN: If this flag is set to TRUE during the copy/move operation, the operation is canceled. // Otherwise, the copy/move operation will continue to completion. bool cancel = false; // Determine Copy or Move action. bool doCopy = copyOptions != null; bool doMove = !doCopy && moveOptions != null; if ((!doCopy && !doMove) || (doCopy && doMove)) throw new NotSupportedException(Resources.UndeterminedCopyMoveAction); bool overwrite = doCopy ? (((CopyOptions) copyOptions & CopyOptions.FailIfExists) != CopyOptions.FailIfExists) : (((MoveOptions) moveOptions & MoveOptions.ReplaceExisting) == MoveOptions.ReplaceExisting); bool raiseException = progressHandler == null; // Setup callback function for progress notifications. var routine = (progressHandler != null) ? (totalFileSize, totalBytesTransferred, streamSize, streamBytesTransferred, dwStreamNumber, dwCallbackReason, hSourceFile, hDestinationFile, lpData) => progressHandler(totalFileSize, totalBytesTransferred, streamSize, streamBytesTransferred, dwStreamNumber, dwCallbackReason, userProgressData) : (NativeMethods.NativeCopyMoveProgressRoutine) null; #endregion //Setup startCopyMove: uint lastError = Win32Errors.ERROR_SUCCESS; #region Win32 Copy/Move if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista ? doMove // MoveFileWithProgress() / MoveFileTransacted() // In the ANSI version of this function, the name is limited to MAX_PATH characters. // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. // 2013-04-15: MSDN confirms LongPath usage. // CopyFileEx() / CopyFileTransacted() // In the ANSI version of this function, the name is limited to MAX_PATH characters. // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. // 2013-04-15: MSDN confirms LongPath usage. ? NativeMethods.MoveFileWithProgress(sourceFileNameLp, destFileNameLp, routine, IntPtr.Zero, (MoveOptions) moveOptions) : NativeMethods.CopyFileEx(sourceFileNameLp, destFileNameLp, routine, IntPtr.Zero, out cancel, (CopyOptions) copyOptions) : doMove ? NativeMethods.MoveFileTransacted(sourceFileNameLp, destFileNameLp, routine, IntPtr.Zero, (MoveOptions) moveOptions, transaction.SafeHandle) : NativeMethods.CopyFileTransacted(sourceFileNameLp, destFileNameLp, routine, IntPtr.Zero, out cancel, (CopyOptions) copyOptions, transaction.SafeHandle))) { lastError = (uint) Marshal.GetLastWin32Error(); if (lastError == Win32Errors.ERROR_REQUEST_ABORTED) { // If lpProgressRoutine returns PROGRESS_CANCEL due to the user canceling the operation, // CopyFileEx will return zero and GetLastError will return ERROR_REQUEST_ABORTED. // In this case, the partially copied destination file is deleted. // // If lpProgressRoutine returns PROGRESS_STOP due to the user stopping the operation, // CopyFileEx will return zero and GetLastError will return ERROR_REQUEST_ABORTED. // In this case, the partially copied destination file is left intact. cancel = true; } else if (raiseException) { #region Win32Errors switch (lastError) { case Win32Errors.ERROR_FILE_NOT_FOUND: // File.Copy() // File.Move() // MSDN: .NET 3.5+: FileNotFoundException: sourceFileName was not found. NativeError.ThrowException(lastError, sourceFileNameLp); break; case Win32Errors.ERROR_PATH_NOT_FOUND: // File.Copy() // File.Move() // Directory.Move() // MSDN: .NET 3.5+: DirectoryNotFoundException: The path specified in sourceFileName or destinationFileName is invalid (for example, it is on an unmapped drive). NativeError.ThrowException(lastError, sourceFileNameLp); break; case Win32Errors.ERROR_FILE_EXISTS: // File.Copy() // Directory.Copy() NativeError.ThrowException(lastError, destFileNameLp); break; default: // For a number of error codes (sharing violation, path not found, etc) // we don't know if the problem was with the source or dest file. // Check if destination directory already exists. // Directory.Move() // MSDN: .NET 3.5+: IOException: destDirName already exists. if (ExistsInternal(true, transaction, destFileNameLp, PathFormat.LongFullPath)) NativeError.ThrowException(Win32Errors.ERROR_ALREADY_EXISTS, destFileNameLp); if (doMove) { // Ensure that the source file or directory exists. // Directory.Move() // MSDN: .NET 3.5+: DirectoryNotFoundException: The path specified by sourceDirName is invalid (for example, it is on an unmapped drive). if (!ExistsInternal(isFolder, transaction, sourceFileNameLp, PathFormat.LongFullPath)) NativeError.ThrowException(isFolder ? Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_FILE_NOT_FOUND, sourceFileNameLp); } // Try reading the source file. string fileNameLp = destFileNameLp; if (!isFolder) { using (SafeFileHandle safeHandle = CreateFileInternal(transaction, sourceFileNameLp, ExtendedFileAttributes.None, null, FileMode.Open, 0, FileShare.Read, false, PathFormat.LongFullPath)) if (safeHandle.IsInvalid) fileNameLp = sourceFileNameLp; } if (lastError == Win32Errors.ERROR_ACCESS_DENIED) { // File.Copy() // File.Move() // MSDN: .NET 3.5+: IOException: An I/O error has occurred. // Directory exists with the same name as the file. if (!isFolder && ExistsInternal(true, transaction, destFileNameLp, PathFormat.LongFullPath)) NativeError.ThrowException(lastError, string.Format(CultureInfo.CurrentCulture, Resources.DirectoryExistsWithSameNameSpecifiedByPath, destFileNameLp)); else { var data = new NativeMethods.Win32FileAttributeData(); FillAttributeInfoInternal(transaction, destFileNameLp, ref data, false, true); if (data.FileAttributes != (FileAttributes) (-1)) { if ((data.FileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { // MSDN: .NET 3.5+: IOException: The directory specified by path is read-only. if (overwrite) { // Reset file system object attributes. SetAttributesInternal(isFolder, transaction, destFileNameLp, FileAttributes.Normal, true, PathFormat.LongFullPath); goto startCopyMove; } // MSDN: .NET 3.5+: UnauthorizedAccessException: destinationFileName is read-only. // MSDN: Win32 CopyFileXxx: This function fails with ERROR_ACCESS_DENIED if the destination file already exists // and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_READONLY attribute set. throw new FileReadOnlyException(destFileNameLp); } // MSDN: Win32 CopyFileXxx: This function fails with ERROR_ACCESS_DENIED if the destination file already exists // and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_READONLY attribute set. if ((data.FileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden) NativeError.ThrowException(lastError, string.Format(CultureInfo.CurrentCulture, Resources.FileHidden, destFileNameLp)); } // Observation: .NET 3.5+: For files: UnauthorizedAccessException: The caller does not have the required permission. // Observation: .NET 3.5+: For directories: IOException: The caller does not have the required permission. NativeError.ThrowException(lastError, destFileNameLp); } } // MSDN: .NET 3.5+: An I/O error has occurred. // File.Copy(): IOException: destinationFileName exists and overwrite is false. // File.Move(): The destination file already exists or sourceFileName was not found. NativeError.ThrowException(lastError, fileNameLp); break; } #endregion // Win32Errors } } #endregion // Win32 Copy/Move #region Transfer Timestamps // Apply original Timestamps if requested. // MoveFileWithProgress() / MoveFileTransacted() automatically preserve Timestamps. // File.Copy() if (preserveDates && doCopy && lastError == Win32Errors.ERROR_SUCCESS) { // Currently preserveDates is only used with files. var data = new NativeMethods.Win32FileAttributeData(); int dataInitialised = FillAttributeInfoInternal(transaction, sourceFileNameLp, ref data, false, true); if (dataInitialised == Win32Errors.ERROR_SUCCESS && data.FileAttributes != (FileAttributes) (-1)) SetFsoDateTimeInternal(false, transaction, destFileNameLp, DateTime.FromFileTimeUtc(data.CreationTime), DateTime.FromFileTimeUtc(data.LastAccessTime), DateTime.FromFileTimeUtc(data.LastWriteTime), PathFormat.LongFullPath); } #endregion // Transfer Timestamps // The copy/move operation succeeded, failed or was canceled. return new CopyMoveResult(sourceFileNameLp, destFileNameLp, isFolder, doMove, cancel, (int) lastError); }
internal static CopyMoveResult CopyMoveInternal(KernelTransaction transaction, string sourcePath, string destinationPath, CopyOptions? copyOptions, MoveOptions? moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { #region Setup if (pathFormat == PathFormat.RelativePath) { Path.CheckValidPath(sourcePath, true, true); Path.CheckValidPath(destinationPath, true, true); } else { // MSDN:. NET 3.5+: NotSupportedException: Path contains a colon character (:) that is not part of a drive label ("C:\"). Path.CheckValidPath(sourcePath, false, false); Path.CheckValidPath(destinationPath, false, false); } // MSDN: .NET 4+ Trailing spaces are removed from the end of the path parameters before moving the directory. // TrimEnd() is also applied for AlphaFS implementation of method Directory.Copy(), .NET does not have this method. var options = GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator; string sourcePathLp = Path.GetExtendedLengthPathInternal(transaction, sourcePath, pathFormat, options); string destinationPathLp = Path.GetExtendedLengthPathInternal(transaction, destinationPath, pathFormat, options); // MSDN: .NET3.5+: IOException: The sourceDirName and destDirName parameters refer to the same file or directory. if (sourcePathLp.Equals(destinationPathLp, StringComparison.OrdinalIgnoreCase)) NativeError.ThrowException(Win32Errors.ERROR_SAME_DRIVE, destinationPathLp); // Determine Copy or Move action. bool doCopy = copyOptions != null; bool doMove = !doCopy && moveOptions != null; if ((!doCopy && !doMove) || (doCopy && doMove)) throw new NotSupportedException(Resources.UndeterminedCopyMoveAction); bool overwrite = doCopy ? (((CopyOptions)copyOptions & CopyOptions.FailIfExists) != CopyOptions.FailIfExists) : (((MoveOptions)moveOptions & MoveOptions.ReplaceExisting) == MoveOptions.ReplaceExisting); var cmr = new CopyMoveResult(sourcePathLp, destinationPathLp, true, doMove, false, (int)Win32Errors.ERROR_SUCCESS); #endregion //Setup #region Copy if (doCopy) { CreateDirectoryInternal(transaction, destinationPathLp, null, null, false, PathFormat.LongFullPath); foreach (var fsei in EnumerateFileSystemEntryInfosInternal<FileSystemEntryInfo>(transaction, sourcePathLp, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.LongFullPath)) { string newDestinationPathLp = Path.CombineInternal(false, destinationPathLp, fsei.FileName); cmr = fsei.IsDirectory ? CopyMoveInternal(transaction, fsei.LongFullPath, newDestinationPathLp, copyOptions, null, progressHandler, userProgressData, PathFormat.LongFullPath) : File.CopyMoveInternal(false, transaction, fsei.LongFullPath, newDestinationPathLp, false, copyOptions, null, progressHandler, userProgressData, PathFormat.LongFullPath); if (cmr.IsCanceled) return cmr; } } #endregion // Copy #region Move else { // MSDN: .NET3.5+: IOException: An attempt was made to move a directory to a different volume. if (((MoveOptions)moveOptions & MoveOptions.CopyAllowed) != MoveOptions.CopyAllowed) if (!Path.GetPathRoot(sourcePathLp, false).Equals(Path.GetPathRoot(destinationPathLp, false), StringComparison.OrdinalIgnoreCase)) NativeError.ThrowException(Win32Errors.ERROR_NOT_SAME_DEVICE, destinationPathLp); // MoveOptions.ReplaceExisting: This value cannot be used if lpNewFileName or lpExistingFileName names a directory. if (overwrite && File.ExistsInternal(true, transaction, destinationPathLp, PathFormat.LongFullPath)) DeleteDirectoryInternal(null, transaction, destinationPathLp, true, true, false, true, PathFormat.LongFullPath); // Moves a file or directory, including its children. // Copies an existing directory, including its children to a new directory. cmr = File.CopyMoveInternal(true, transaction, sourcePathLp, destinationPathLp, false, null, moveOptions, progressHandler, userProgressData, PathFormat.LongFullPath); } #endregion // Move // The copy/move operation succeeded or was canceled. return cmr; }
private CopyMoveResult CopyToMoveToInternal(string destinationPath, CopyOptions? copyOptions, MoveOptions? moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, out string longFullPath, PathFormat pathFormat) { string destinationPathLp = Path.GetExtendedLengthPathInternal(null, destinationPath, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); longFullPath = destinationPathLp; // Returns false when CopyMoveProgressResult is PROGRESS_CANCEL or PROGRESS_STOP. return Directory.CopyMoveInternal(Transaction, LongFullName, destinationPathLp, copyOptions, moveOptions, progressHandler, userProgressData, PathFormat.LongFullPath); }
public static void Move(KernelTransaction transaction, string sourceFileName, string destinationFileName, MoveOptions moveOptions, PathFormat pathFormat) { CopyMoveInternal(false, transaction, sourceFileName, destinationFileName, false, null, moveOptions, null, null, pathFormat); }
public static CopyMoveResult Move(KernelTransaction transaction, string sourceFileName, string destinationFileName, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveInternal(false, transaction, sourceFileName, destinationFileName, false, null, moveOptions, progressHandler, userProgressData, PathFormat.RelativePath); }
public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { string destinationPathLp; CopyMoveResult cmr = CopyToMoveToInternal(destinationPath, null, moveOptions, progressHandler, userProgressData, out destinationPathLp, pathFormat); CopyToMoveToInternalRefresh(destinationPath, destinationPathLp); return cmr; }
public FileInfo MoveTo(string destinationPath, MoveOptions moveOptions) { string destinationPathLp; CopyToMoveToInternal(destinationPath, false, null, moveOptions, null, null, out destinationPathLp, PathFormat.RelativePath); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); }
public static void Move(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { CopyMoveInternal(transaction, sourcePath, destinationPath, null, moveOptions, null, null, pathFormat); }
public static void Move(string sourcePath, string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { CopyMoveInternal(null, sourcePath, destinationPath, null, moveOptions, null, null, pathFormat); }
public static CopyMoveResult Move(KernelTransaction transaction, string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveInternal(transaction, sourcePath, destinationPath, null, moveOptions, progressHandler, userProgressData, pathFormat); }
public static CopyMoveResult Move(string sourcePath, string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { return CopyMoveInternal(null, sourcePath, destinationPath, null, moveOptions, progressHandler, userProgressData, PathFormat.RelativePath); }
public DirectoryInfo MoveTo(string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToInternal(destinationPath, null, moveOptions, null, null, out destinationPathLp, pathFormat); return new DirectoryInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); }