1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
using System;
using System.IO;
namespace ViperBytes.IO
{
public class AutoRenamer
{
/// <summary>
/// Returns a new, not existing path.
/// On the end of the file / directory name will be attached a number
/// </summary>
/// <param name="path">The existing path</param>
/// <returns>An alternative path wich not exists</returns>
public static string AutoRename(string path)
{
if ((!File.Exists(path)) && (!Directory.Exists(path)))
// the path doesn't exist, so return without attached counter
return path;
else if (path == Path.GetPathRoot(path))
// the path is only a drive letter, so we can't attach something
return path;
// the returned alternative path
string alternative = path;
// the attach counter
int count = 0;
// specifyes, wheather an ending slash of directory was cutten
bool cutSlash = false;
// cut ending slash
if (alternative[alternative.Length - 1] == Path.DirectorySeparatorChar)
{
alternative = alternative.Substring(0, alternative.Length - 1);
// remember, because we have to replace it later
cutSlash = true;
}
while ((File.Exists(alternative)) || (Directory.Exists(alternative)))
{
count++;
// the attachment from count
string attach = " (" + count.ToString() + ")";
// cut extension if file exists
if (File.Exists(alternative))
alternative = path.Substring(0, path.Length - Path.GetExtension(path).Length) + attach + Path.GetExtension(path);
else
alternative = path + attach;
}
// if a slash was cutten, add it at the end
if (cutSlash)
alternative += Path.DirectorySeparatorChar;
return alternative;
}
}
}
|