Checking to see if a filename already exists before replacing an invalid char
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开发者_StackOverflow (versus a blank). Code would really help.Thank you!
You can use File.Exists
to 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:
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
if (!System.IO.File.Exists(sanitized))
{
// perform the move
System.IO.File.Move(files2, sanitized);
}
else
{
// perform other action
}
And as ChrisF helpfully mentioned in the comments section to your question, you can use Path.GetInvalidFileNameChars
and Path.GetInvalidPathChars
for making sure the filename is valid.
if (System.IO.File.Exists(sanitized))
{
// The file already exists!
}
int replacement = 0;
while( File.Exists( sanitized ) )
{
int lastDot = sanitized.LastIndexOf('.');
if( lastDot < 0 )
lastDot=sanitized.Length;
sanitized = String.Format("{0}{1}{2}",
sanitized.Substring(0,lastDot - (replacement>0?1:0)),
replacement++,
sanitized.Substring(lastDot)
);
}
精彩评论