feat: 初始功能
This commit is contained in:
35
Services/PathHelper.cs
Normal file
35
Services/PathHelper.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user