Removes invalid file name characters from the specified string.
#region License
// (c) Intergen.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
#endregion
using System;
using System.Text;
using System.IO;
using System.Web;
using System.Web.Hosting;
namespace Utilities.IO
{
public class FileUtils
{
/// <summary>
/// Removes invalid file name characters from the specified string.
/// </summary>
/// <param name="s">The filename string.</param>
/// <returns></returns>
public static string ToValidFileName(string s)
{
return ToValidFileName(s, string.Empty, null);
}
public static string ToValidFileName(string s, string invalidReplacement)
{
return ToValidFileName(s, invalidReplacement, null);
}
public static string ToValidFileName(string s, string invalidReplacement, string spaceReplacement)
{
StringBuilder sb = new StringBuilder(s);
foreach (char invalidFileNameChar in Path.GetInvalidFileNameChars())
{
if (invalidReplacement != null)
sb.Replace(invalidFileNameChar.ToString(), invalidReplacement);
}
if (spaceReplacement != null)
sb.Replace(" ", spaceReplacement);
return sb.ToString();
}
}
}
Related examples in the same category