开发者

Having Trouble Renaming Files that Match with my RegEx

开发者 https://www.devze.com 2023-01-05 07:40 出处:网络
I have an app that \"cleans\" \"dirty\" filenames.\"Dirty\" filenames have #%&~+{} in their filenames.What my app does is see if they are a match for a RegEx pattern i have defined and then send i

I have an app that "cleans" "dirty" filenames. "Dirty" filenames have #%&~+{} in their filenames. What my app does is see if they are a match for a RegEx pattern i have defined and then send it to a method called FileCleanUp where it "cleans" the file and replaces invalid chars with a "". However, i noticed while i was running this, that my FileCleanup method only works on SOME files and not others!

Here is my code:

    public class SanitizeFileNames
{

    public void FileCleanup(List<string>paths)
    {
        string regPattern = (@"[~#&!%+{}]+");
        string replacement = "";
        Regex regExPattern = new Regex(regPattern);


        foreach (string files2 in paths)
            try
            {
                string file开发者_StackOverflow社区nameOnly = 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);
            }
            catch (Exception e)
            { 
            //write to streamwriter

            }

            }

I tested on a few files with the names like: ~Test.txt, #Test.txt, +Text.txt, Test&Test.txt, T{e}st.txt, Test%.txt.

The ones i could not get to be renamed were: ~Test.txt, +Test.txt, T{e}st.txt

I debugged this and weirdly enough, it shows that these files that did not get renamed for some reason as correct on the debugger. Instead of showing ~Test.txt as a "sanitized" file name, it was Text.txt. So on the app side, it DOES read my foreach loop correctly.

However, i'm really stumped as to why it's not actually renaming these files. Anybody have a clue as to why this might be? Does it have to do with the File.Move() ?

EDIT: On further testing, i realize that it also doesn't rename files that are like this: ~~test.txt or ##test.txt


You have an empty catch block. Why don't you print out the exception message to see what's happening?

My guess is that the file names are matching the regex, but you're unable to rename the files because a file named Test.txt already exists after #Test.txt is renamed to that. Try renaming the other files to ~Test2.txt, +Test3.txt, T{e}st4.txt before running the program again.

0

精彩评论

暂无评论...
验证码 换一张
取 消