Skip to content

Instantly share code, notes, and snippets.

@tiagosalgado
Created January 8, 2013 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagosalgado/4484413 to your computer and use it in GitHub Desktop.
Save tiagosalgado/4484413 to your computer and use it in GitHub Desktop.
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