60 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Volian.Base.Library
{
// Part of fix for B2019-032 - will clean up the passed in file name.
public static class ValidFileName
{
/// <summary>
/// Replaces characters in orgTxt that are not allowed in file names with the specified replacement character.
/// </summary>
/// <remarks>
/// Note that Forward Slash, Back Slash and Pipe (vertical bar) are replaced with a dash '-'.
/// The Double quote is replaced with a single quote.
/// Everything else is replaced with a '_' unless a different replace char is passed in.
/// A null (zero) replacement character will cause the invalid characters to be removed.
/// The list of invalid characters include Double Quote, Less Than, Greater Than, Pipe, Question Mark, Back and Forward Slashes, Colin.
/// Also invalid are characters less than Ascii 32 (space) and greater than Ascii 126 (tilde)
/// </remarks>
/// <param name="orgTxt">Text to make into a valid filename. The same string is returned if it is valid already.</param>
/// <param name="replacementChar">Replacement character ('_' is the default), or null to simply remove bad characters.</param>
/// <param name="additionalInvalidChars">Character array of additional character to replace.</param>
/// <returns>A string that can be used as a filename. If the output string would otherwise be empty, returns "_".</returns>
public static string FixFileName(string orgTxt, char? replacementChar = '_', char[] additionalInvalidChars = null)
{
StringBuilder sb = new StringBuilder(orgTxt.Length);
bool changed = false;
//var invalidChars = System.IO.Path.GetInvalidFileNameChars();
char[] invalidChars = { '"', '<', '>', '|', '?', '\\', '/', ':' };
if (additionalInvalidChars != null) invalidChars = invalidChars.Union(additionalInvalidChars).ToArray();
for (int i = 0; i < orgTxt.Length; i++)
{
char c = orgTxt[i];
if (invalidChars.Contains(c) || !(c >= ' ' && c <= '~'))
{
changed = true;
var repl = replacementChar ?? '\0';
if (repl != '\0')
{
if (c == '\\' || c == '/' || c == '|')
sb.Append('-'); // replace forward slash, back slash, and vertical line (pipe) with a dash
else if (c == '"')
sb.Append('\''); // replace a double quote with a single quote
else
sb.Append(repl); // replace with '_' or passed in replacement character
}
}
else
sb.Append(c); // the character is OK just add it to the return string
}
if (sb.Length == 0)
return "_"; // return a '_' if return string is empty.
return changed ? sb.ToString() : orgTxt; // if we replaced a character return the corrected file name, else return the original file name
}
}
}