mirror of
https://github.com/microsoft/PowerToys.git
synced 2026-04-03 09:46:54 +02:00
[ImageResizer]Sanitize target file name (#14040)
* [ImageResizer] Sanitize target file name * Add a test * Avoid not recommended file names
This commit is contained in:
@@ -26,6 +26,14 @@ namespace ImageResizer.Models
|
||||
private readonly string _destinationDirectory;
|
||||
private readonly Settings _settings;
|
||||
|
||||
// Filenames to avoid according to https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#file-and-directory-names
|
||||
private static readonly string[] _avoidFilenames =
|
||||
{
|
||||
"CON", "PRN", "AUX", "NUL",
|
||||
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
|
||||
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
|
||||
};
|
||||
|
||||
public ResizeOperation(string file, string destinationDirectory, Settings settings)
|
||||
{
|
||||
_file = file;
|
||||
@@ -205,16 +213,39 @@ namespace ImageResizer.Models
|
||||
extension = supportedExtensions.FirstOrDefault();
|
||||
}
|
||||
|
||||
// Remove directory characters from the size's name.
|
||||
string sizeNameSanitized = _settings.SelectedSize.Name;
|
||||
sizeNameSanitized = sizeNameSanitized
|
||||
.Replace('\\', '_')
|
||||
.Replace('/', '_');
|
||||
|
||||
// Using CurrentCulture since this is user facing
|
||||
var fileName = string.Format(
|
||||
CultureInfo.CurrentCulture,
|
||||
_settings.FileNameFormat,
|
||||
originalFileName,
|
||||
_settings.SelectedSize.Name,
|
||||
sizeNameSanitized,
|
||||
_settings.SelectedSize.Width,
|
||||
_settings.SelectedSize.Height,
|
||||
encoder.Frames[0].PixelWidth,
|
||||
encoder.Frames[0].PixelHeight);
|
||||
|
||||
// Remove invalid characters from the final file name.
|
||||
fileName = fileName
|
||||
.Replace(':', '_')
|
||||
.Replace('*', '_')
|
||||
.Replace('?', '_')
|
||||
.Replace('"', '_')
|
||||
.Replace('<', '_')
|
||||
.Replace('>', '_')
|
||||
.Replace('|', '_');
|
||||
|
||||
// Avoid creating not recommended filenames
|
||||
if (_avoidFilenames.Contains(fileName.ToUpperInvariant()))
|
||||
{
|
||||
fileName = fileName + "_";
|
||||
}
|
||||
|
||||
var path = _fileSystem.Path.Combine(directory, fileName + extension);
|
||||
var uniquifier = 1;
|
||||
while (_fileSystem.File.Exists(path))
|
||||
|
||||
Reference in New Issue
Block a user