Mit diesem Snippet ist es möglich, einen Pfad, sei es eine Datei oder ein Verzeichnis, umzugestalten, so dass dieser nicht mehr existiert.
Wenn ein Pfad nicht existiert, wird er unverändert zurückgegeben, andernfalls wird eine Nummer angehängt.
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;
}
}
}
1 Kommentare zum Snippet