profile for Cullen Tsering at Stack Overflow, Q&A for professional and enthusiast programmers

Wednesday, April 24, 2013

File Name and Directory Name Helper


Often times, I want to create folder or file names from some string but file and directory names need to be valid so I've created the following helper class to help me.

 public static class FilePathNameHelper
 {

  public static string GetValidPathName(string pathName, char goodCharReplacement)
  {
   return ReplaceBadWithGood(pathName, Path.GetInvalidPathChars(), goodCharReplacement); 
  }

  public static string GetValidFileName(string fileName, char goodCharReplacement)
  {
   return ReplaceBadWithGood(fileName, Path.GetInvalidFileNameChars(), goodCharReplacement);
  }

  private static string ReplaceBadWithGood(string subject, char[] badBoys, char good)
  {
   if (!string.IsNullOrWhiteSpace(subject)
    && subject.ToCharArray().Intersect(badBoys).Any())
   {
    subject = badBoys.Aggregate(subject, (current, bad) => current.Replace(bad, good));
   }
   return subject;
  }
 }
It's quite easy to use:
var goodFileName = FilePathNameHelper.GetValidFileName("some bad file name<>.txt",'-');

goodFileName should contain "some bad file name--.txt".

About Cullen

My photo
Christian, Father, Software Developer/Architect who enjoys technology and using it to make people's lives easier!

Followers