Created
January 8, 2013 15:00
-
-
Save tiagosalgado/4484413 to your computer and use it in GitHub Desktop.
Rename files to avoid overwritten ones already saved http://blog.tiagosalgado.com/2013/01/08/replace-filenames-to-avoid-overwrite-the-ones-already-saved
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private List<CustomFile> fileList; | |
void Main() | |
{ | |
fileList = LoadFiles(); | |
var filesToAdd = new List<CustomFile>() { | |
new CustomFile { FileName = "file.txt", owner = @"domain\user" }, | |
new CustomFile { FileName = "file1", owner = @"domain\user" }, | |
new CustomFile { FileName = "file.txt", owner = @"domain\user" } | |
}; | |
foreach(var file in filesToAdd) | |
{ | |
SaveFile(file); | |
} | |
} | |
public void SaveFile(CustomFile file) | |
{ | |
// presist the original filename | |
var originalFileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName); | |
// get number of files with same name | |
var count = fileList.Where(j => j.FileName == file.FileName).Count(); | |
var appendCount = 1; | |
while(count > 0) | |
{ | |
var fileExtension = System.IO.Path.GetExtension(file.FileName); | |
file.FileName = string.Format("{0} ({1}){2}", originalFileName, appendCount, fileExtension); | |
appendCount++; | |
// check again | |
count = fileList.Where(j => j.FileName == file.FileName).Count(); | |
} | |
// add to files temporarily just to ensure that when we upload multiple files with same that, the rename function will be executed correctly | |
fileList.Add(file); | |
} | |
public List<CustomFile> LoadFiles() | |
{ | |
return new List<CustomFile>() { | |
new CustomFile { FileName = "file.txt", owner = @"domain\user" }, | |
new CustomFile { FileName = "file (1).txt", owner = @"domain\user" }, | |
new CustomFile { FileName = "other file.txt", owner = @"domain\user" } | |
}; | |
} | |
// dummy class for file but we don't really need this | |
public class CustomFile | |
{ | |
public string FileName {get; set;} | |
public string owner {get; set;} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment