Fixing / Removing Invalid Characters from a File Path / Name – c#

Below is a simple method for fixing bad filenames and paths. This uses the character lists from Path.GetInvalidPathChars and Path.GetInvalidFileNameChars (part of System.IO).

You should be able to pass a filename, directory or path. Example, calling these three lines would yield the below:

cleanPath(@"c:\tem|<p\fi<>le.txt")
cleanPath(@"c:\tem|<p\")
cleanPath(@"fi<le.txt")

Returns:

c:\tem-p\fi-le.txt
c:\tem-p\
fi-le.txt

You can also pass a string that’s used to replace the bad characters.

cleanPath(@"c:\tem|<p\fi<>le.txt", string.Empty)

Returns:

c:\temp\file.txt
 private string cleanPath(string toCleanPath, string replaceWith = "-")  
      {  
           //get just the filename - can't use Path.GetFileName since the path might be bad!  
           string[] pathParts = toCleanPath.Split(new char[] { '\\' });  
           string newFileName = pathParts[pathParts.Length - 1];  
           //get just the path  
           string newPath = toCleanPath.Substring(0, toCleanPath.Length - newFileName.Length);   
           //clean bad path chars  
           foreach (char badChar in Path.GetInvalidPathChars())  
           {  
                newPath = newPath.Replace(badChar.ToString(), replaceWith);  
           }  
           //clean bad filename chars  
           foreach (char badChar in Path.GetInvalidFileNameChars())  
           {  
                newFileName = newFileName.Replace(badChar.ToString(), replaceWith);  
           }  
           //remove duplicate "replaceWith" characters. ie: change "test-----file.txt" to "test-file.txt"  
           if (string.IsNullOrWhiteSpace(replaceWith) == false)  
           {  
                newPath = newPath.Replace(replaceWith.ToString() + replaceWith.ToString(), replaceWith.ToString());  
                newFileName = newFileName.Replace(replaceWith.ToString() + replaceWith.ToString(), replaceWith.ToString());  
           }  
           //return new, clean path:  
           return newPath + newFileName;  
      }  

Hope it helps!

Fixing / Removing Invalid Characters from a File Path / Name – c#

Watching & Printing New Files in a Directory – vb & c#

FileWatcherPrinterMonitoring a folder for new files in .net can easily be watched using the FileSystemWatcher in System.IO. You give it a path (ie: C:\toprint) and it will raise an event when a file is created (you can also watch for deleted, renamed and updated files).

Edit: I have new / full code here on GitHub.

I’ve had the need on several occasions to print new files as they are created, so the combination of the FileSystemWatcher and using a process to call the file and print work well together. Below the code to print to the default printer (works great for .pdf files):

c#:

 Process PrintProcess = new Process();
 PrintProcess.StartInfo.CreateNoWindow = false;
 PrintProcess.StartInfo.Verb = "print";
 PrintProcess.StartInfo.FileName = e.FullPath;
 PrintProcess.Start();

vb:

 Dim PrintProcess As New Process
 PrintProcess.StartInfo.CreateNoWindow = False
 PrintProcess.StartInfo.Verb = "print"
 PrintProcess.StartInfo.FileName = e.FullPath
 PrintProcess.Start()

The file watcher uses this syntax:

c#:

FileSystemWatcher fsWatcher = new FileSystemWatcher(txtDirToWatch.Text);
fsWatcher.Created += OnChanged;
 var withFSW = fsWatcher;
 withFSW.EnableRaisingEvents = true;
 withFSW.IncludeSubdirectories = false;
 withFSW.WaitForChanged(WatcherChangeTypes.Created);
 withFSW.Filter = "*.pdf";

vb:

Dim fsWatcher As New FileSystemWatcher(txtDirToWatch.Text)
 
AddHandler fsWatcher.Created, AddressOf OnChanged
With fsWatcher
 .EnableRaisingEvents = True
 .IncludeSubdirectories = False
 .WaitForChanged(WatcherChangeTypes.Created)
 .Filter = "*.pdf"
End With

And the OnChanged Event: c#:

 public void OnChanged(object source, FileSystemEventArgs e)
 {
   //Do something with e.FullPath, etc.
 }

 

vb:

 Public Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
  'Do something with e.FullPath, etc.
 End Sub

 

*I haven’t used this method to print many different formats or tons of files at once, but give it a try!

If you’d like a fully working solution (vb or c#) drop me a line at chris.bitting(at)gmail(dot)com and I’d be glad to send my project and code.

Watching & Printing New Files in a Directory – vb & c#