I have a project where I'm recursing into drives specified by the user and am getting rid of any "invalid" characters defined in a RegEx pattern.

I'm very new to this and C#, so any help would be appreciated!
If the file contains ANY of these characters: | # { } % & " ~ + \ / : * ? " < > , they need to be replaced with " ". However, I'm finding it hard with my current code for it to do this. First off, my datagridview doesn't show ONLY files that have any of those chars in it. It tends to show everything in the drive/folder i've selected. Why is that?

Also, am i using the correct RegEx pattern? If not, can someone help me and give me the correct pattern?

Form1's code:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderSelect("Please select:");
            
        }

        public string FolderSelect(string txtPrompt)
        {
            //Value to be returned
            string result = string.Empty;

            //Now, we want to use the path information to population our folder selection initial location
            string initialPathDir = (@"C:\");
            System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(initialPathDir);
            FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
            FolderSelect.SelectedPath = info.FullName;
            FolderSelect.Description = txtPrompt;
            FolderSelect.ShowNewFolderButton = true;

            if (FolderSelect.ShowDialog() == DialogResult.OK)
            {
                string retPath = FolderSelect.SelectedPath;
                if (retPath == null)
                {
                    retPath = "";
                }
                DriveRecursion_Results dw = new DriveRecursion_Results();
                dw.Show();
                dw.DriveRecursion(retPath);
                
                result = retPath;
                
             }
            
            return result;
            
        }





    }]


DriveRecursion_Results.cs's code:

[namespace FileMigration2
{
    public partial class DriveRecursion_Results : Form
    {
        List<string> paths = new List<string>();  
        
        public DriveRecursion_Results()
        {
            InitializeComponent();

        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        public void DriveRecursion(string retPath)
        {
            string pattern = "[~#%&*{}/<>?|\"-]+";
           
            Regex regEx = new Regex(pattern);

            string[] fileDrive = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
            List<string> filePath = new List<string>();
            List<string> filePaths = new List<string>();
            

            dataGridView1.Rows.Clear();
            try
            {
                foreach (string fileNames in fileDrive)
                {
                    SanitizeFileNames sw = new SanitizeFileNames();
                    
                    
                    if (regEx.IsMatch(fileNames))
                    {
                        string fileNameOnly = Path.GetFileName(fileNames);
                        string pathOnly = Path.GetDirectoryName(fileNames);

                        DataGridViewRow dgr = new DataGridViewRow();
                        filePath.Add(fileNames);
                        dgr.CreateCells(dataGridView1);
                        dgr.Cells[0].Value = pathOnly;
                        dgr.Cells[1].Value = fileNameOnly;
                        dataGridView1.Rows.Add(dgr);
                        //filePath.Add(fileNames);
                        filePaths.Add(fileNames);
                        paths.Add(fileNames);
                        //sw.FileCleanup(filePaths);
                        
                    }
                        
                    else
                    {
                        DataGridViewRow dgr2 = new DataGridViewRow();
                        dgr2.Cells[0].Value = "No Files To Clean Up";
                        dgr2.Cells[1].Value = "";
                    }

                }
                
            }
            catch (Exception e)
            {
                StreamWriter sw = new StreamWriter(retPath + "ErrorLog.txt");
                sw.Write(e);

            }

        }

        public void button1_Click(object sender, EventArgs e)
        {
            new SanitizeFileNames().FileCleanup(paths);
            Application.Exit();
            
        }
       
        

        
    }
}]

Finally, SanitizeFileNames.cs's code:

[namespace FileMigration2
{
    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 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);
                }
                catch (Exception e)
                { 
                //write to streamwriter
                
                }
                    
                }

            //foreach (string sanitizedString in paths)
            //{
            //    if (sanitizedString.Contains(regPattern))
            //    {
            //        List<string> Unclean = new List<string>();
            //        return;
            //    }
            //    else
            //    {
            //        continue;
            //    }
            
            //}
            //} 
           
        
        }
    
    }

I'm a VERY new coder to all of this--so please keep that in mind when answering.

Thank you in advance!

Edited 6 Years Ago by __avd: Added [code] tags. For easy readability, always wrap programming code within posts in [code] (code blocks).

Ok..so is my regex pattern then: @"[~#%+&{}?]+" ?? Do i need to escape any of these if they are special characters?

This article has been dead for over six months. Start a new discussion instead.