yeahumok
yeahumok

Reputation: 2952

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 (versus a blank). Code would really help.

Thank you!

Upvotes: 0

Views: 1131

Answers (3)

maxwellb
maxwellb

Reputation: 13944

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)
        );
}

Upvotes: 0

chrissr
chrissr

Reputation: 9921

if (System.IO.File.Exists(sanitized))
{
    // The file already exists!
}

Upvotes: 1

dcp
dcp

Reputation: 55454

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.

Upvotes: 2

Related Questions