tags:

views:

141

answers:

3

I'm not sure what exactly i'm doing wrong here...but i noticed that my File.Move() isn't renaming any files.
Also, does anybody know how in my 2nd loop, i'd be able to populate my .txt file with a list of the path AND sanitized file name?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
class Program
{
    static void Main(string[] args)
    {

        //recurse through files.  Let user press 'ok' to move onto next step        
        string[] files = Directory.GetFiles(@"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing", "*.*", SearchOption.AllDirectories);
        foreach (string file in files)
        {
            Console.Write(file + "\r\n");
        }
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey(true);
        //End section

        //Regex -- find invalid chars
        string pattern = " *[\\~#%&*{}/<>?|\"-]+ *";
        string replacement = " ";
        Regex regEx = new Regex(pattern);

        string[] fileDrive = Directory.GetFiles(@"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing", "*.*", SearchOption.AllDirectories);
        List<string> filePath = new List<string>();

        //clean out file -- remove the path name so file name only shows
        string result;            
        foreach(string fileNames in fileDrive)
        {
        result = Path.GetFileName(fileNames);
        filePath.Add(result);

        }

        StreamWriter sw = new StreamWriter(@"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing\File_Renames.txt");

        //Sanitize and remove invalid chars
        foreach(string Files2 in filePath)
        {
            try
            {
                string sanitized = regEx.Replace(Files2, replacement);
                sw.Write(sanitized + "\r\n");
                System.IO.File.Move(Files2, sanitized);
                System.IO.File.Delete(Files2);




            }
            catch (Exception ex)
            { 
            Console.Write(ex);
            }


        }
        sw.Close();

    }

}

}

I'm VERY new to C# and trying to write an app that recurses through a specific drive, finds invalid characters (as specified in the RegEx pattern), removes them from the filename and then write a .txt file that has the path name and the corrected filename.

Any ideas?

+2  A: 

Are any exceptions being thrown in the call to File.Move()? You have an empty catch block beneath it which will be stopping you from seeing them. Try removing the catch{} or putting some code in there to log any exceptions.

HullCitySteve
+6  A: 

Your filepath list contains only the file names. You have removed the directory info from them in the call to Path.GetFileName(), so your File.Move is looking for the target file in the application's default directory, rather than its original location.

I think your code for saving the sanitized file names is correct though. You should use the using() construct around your StreamWriter though, as below, to ensure that the file is closed once you're done with it.

//clean out file -- remove the path name so file name only shows
string result;            
foreach(string fileNames in fileDrive)
{
    // result = Path.GetFileName(fileNames); // don't do this.
    filePath.Add(fileNames);
}

using (StreamWriter sw = new StreamWriter(@"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing\File_Renames.txt"))
{
        //Sanitize and remove invalid chars  
        foreach(string Files2 in filePath)  
        {  
            try  
            {  
                string filenameOnly = Path.GetFileName(Files2);
                string pathOnly = Path.GetDirectoryName(Files2);
                string sanitizedFilename = regEx.Replace(filenameOnly, replacement);
                string sanitized = Path.Combine(pathOnly, sanitizedFilename);  
                sw.Write(sanitized + "\r\n");  
                System.IO.File.Move(Files2, sanitized);  
            }  
            catch  
            {   
            }  
        }  
}
Neil Moss
so then, should i NOT use the GetFileName() and instead pass the entire path to File.Move()?
@Neil: Good eye!@yeahumok: That is correct. ;)
Lance May
Just make sure you don't accidentally sanitize the folder name too or you'll get an error, because you'll be trying to move the file to a 'sanitized' folder that doesn't exist (if it has any 'invalid' characters). Something along the lines of `File.Move(Path.Combine(folder, Files2), Path.Combine(folder. sanitized))` where `folder` is the same one you used above.
Flynn1179
i just tried this--however it's still not actually renaming the filename. It renames it in the .txt file...but not the file itself. is there something that perhaps i'm missing?
Did you pass in the entire path? check the code sample now, and see how you go.
Neil Moss
THANK YOU SO MUCH. this worked just great!!! and thank you everybody for the help! i'm a newbie and it's wonderful to know that others are willing to help :)
Welcome to SO. :-)
Neil Moss
Remove the 'Delete(Files2)' line; it superfluous, and should technically cause an exception every time; not to mention it's extremely dangerous if your file didn't have any special characters. File.Move does nothing if the two filenames are the same, but you'll then delete the original!Also, use `Console.WriteLine(ex.Message)`, and pay close attention to the output window for any errors. Writing (ex) on it's own won't actually give you the error message.Edit: Heh, posted 5 minutes too late :)
Flynn1179
+1  A: 

Try using File.AppendAllLines() (with a collection) or File.AppendAllText() (for each individually) instead of a stream. That will make things a little easier.

Also, I understand not wanting your application to bomb, but at the very least, while you're currently writing/debugging comment your try block out so that you can see the exceptions.

Probably not an answer, but perhaps a suggestion to help.

Lance May