public async Task RenameAsync(string newName, NameCollisionOption collisionOption = NameCollisionOption.FailIfExists, CancellationToken cancellationToken = default(CancellationToken)) { bool alreadyExists = false; string finalName = newName; int counter = 1; do { counter++; alreadyExists = file.ParentFile.FindFile(finalName) != null; if (alreadyExists) { switch (collisionOption) { case NameCollisionOption.GenerateUniqueName: finalName = $"{System.IO.Path.GetFileNameWithoutExtension(newName)} ({counter}){System.IO.Path.GetExtension(newName)}"; break; case NameCollisionOption.ReplaceExisting: file.ParentFile.FindFile(finalName).Delete(); break; case NameCollisionOption.FailIfExists: throw new AlreadyExistsException(); default: break; } } } while (alreadyExists); file.RenameTo(newName); }
/// <summary> /// Ändert den Objektnamen (API level 14) /// </summary> /// <param name="storagename">z.B. "primary" oder "19F4-0903"</param> /// <param name="volpath">abs. Pfad im Volume</param> /// <param name="newfilename"></param> /// <returns></returns> public bool Rename(string storagename, string volpath, string newfilename) { if (newfilename.Contains('/')) { throw new Exception("Path for newname is not allowed."); } /* * boolean renameTo (String displayName) * * Renames this file to displayName. * Note that this method does not throw IOException on failure. Callers must check the return value. * Some providers may need to create a new document to reflect the rename, potentially with a different MIME type, so getUri() and getType() may change to reflect the rename. * When renaming a directory, children previously enumerated through listFiles() may no longer be valid. * * Parameters * displayName String: the new display name. * * Returns * boolean true on success. */ DocumentFile doc = GetExistingDocumentFile(storagename, volpath); bool ok = doc.RenameTo(newfilename); System.Diagnostics.Debug.WriteLine("AndroidRename(" + storagename + ", " + volpath + ", " + newfilename + ") = " + ok.ToString()); return(ok); }