I have this code:
public void FileCleanup(List<string>paths)
{
string regPattern = (@"[~#&!%+{}]+");
string replacement = "";
Regex regExPattern = new Regex(regPattern);
foreach (string files2 in paths)
try
{
string filenameOnly = Path.GetFileName(files2);
string pathOnly = Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
//write to streamwriter
System.IO.File.Move(files2, sanitized);
}
Now, my question is, how do i make sure that before the .Replace(), that the app first checks to see if the filename does NOT exist?
I noticed my app, when given these test files: ###test.txt, #~test.txt will NOT remove invalid chars because after a rename, they will both have the same filename (test.txt).
If it does, i want it to go to another foreach loop where i switch the invalid char to a specific char (versus a blank). Code would really help.
Thank you!
You can use
File.Existsto check to see if the file already exists. Here’s the reference:http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx
So in your example:
And as ChrisF helpfully mentioned in the comments section to your question, you can use
Path.GetInvalidFileNameCharsandPath.GetInvalidPathCharsfor making sure the filename is valid.