Why isn't my File.Move() working?

Posted by yeahumok on Stack Overflow See other posts from Stack Overflow or by yeahumok
Published on 2010-06-16T15:01:37Z Indexed on 2010/06/16 15:12 UTC
Read the original article Hit count: 218

Filed under:

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?

© Stack Overflow or respective owner

Related posts about c#