35 lines
1.0 KiB
C#
35 lines
1.0 KiB
C#
|
|
using System.IO;
|
||
|
|
|
||
|
|
namespace CloudPrint.Client.Services;
|
||
|
|
|
||
|
|
public static class PathHelper
|
||
|
|
{
|
||
|
|
public static string CreateUniqueFilePath(string directory, string fileName)
|
||
|
|
{
|
||
|
|
Directory.CreateDirectory(directory);
|
||
|
|
|
||
|
|
var safeFileName = SanitizeFileName(string.IsNullOrWhiteSpace(fileName) ? "untitled" : fileName);
|
||
|
|
var name = Path.GetFileNameWithoutExtension(safeFileName);
|
||
|
|
var extension = Path.GetExtension(safeFileName);
|
||
|
|
var candidate = Path.Combine(directory, safeFileName);
|
||
|
|
var index = 1;
|
||
|
|
|
||
|
|
while (File.Exists(candidate))
|
||
|
|
{
|
||
|
|
candidate = Path.Combine(directory, $"{name}_{index++}{extension}");
|
||
|
|
}
|
||
|
|
|
||
|
|
return candidate;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static string SanitizePathSegment(string value)
|
||
|
|
{
|
||
|
|
var invalidChars = Path.GetInvalidFileNameChars();
|
||
|
|
return new string(value.Select(ch => invalidChars.Contains(ch) ? '_' : ch).ToArray());
|
||
|
|
}
|
||
|
|
|
||
|
|
private static string SanitizeFileName(string fileName)
|
||
|
|
{
|
||
|
|
return SanitizePathSegment(fileName);
|
||
|
|
}
|
||
|
|
}
|