none
Replace " " character to "_" in an string array and change file names on a directory according to this. RRS feed

  • Question

  • So i have code like this:
    string scLoc = AppDomain.CurrentDomain.BaseDirectory + @"shortcuts";
    
    string[] crDirectory = Directory.GetFiles(scLoc);
    
    foreach (string fileDir in crDirectory)
                    {
                        System.IO.File.Move(fileDir, fileDir.ToLowerInvariant());
                    }
    
    string[] crFile = Directory.GetFiles(scLoc).Select(System.IO.Path.GetFileNameWithoutExtension).ToArray();
    
    for (UInt16 i = 0; i < crFile.Count<string>(); i++)
                    {
                        crFile[i] = crFile[i].Replace(" ", "_");
                    }
    I get the scLoc data from a directory in my pc, when the foreach happens program changes all the letters to lower, then i get just the file part of the full adres and replace all the " " s to "_" however i don't know how to change all the real files in the compter names to these underscore versions. Also i cannot do that inside the first foreach because its changeing the whole adress to underscored version and that's a problem. Is there a efficient and dirty way to do this?
    Thursday, January 24, 2019 6:01 PM

Answers

  • Check this:

    DirectoryInfo directory = new DirectoryInfo( scLoc );
    FileInfo[] files = directory.GetFiles();
    
    foreach( var file in files )
    {
        var new_path = Path.Combine( directory.FullName, file.Name.Replace( ' ', '_' ) );
        file.MoveTo( new_path );
    }
    

    • Marked as answer by xanrer Thursday, January 24, 2019 10:12 PM
    Thursday, January 24, 2019 8:01 PM

All replies

  • Check this:

    DirectoryInfo directory = new DirectoryInfo( scLoc );
    FileInfo[] files = directory.GetFiles();
    
    foreach( var file in files )
    {
        var new_path = Path.Combine( directory.FullName, file.Name.Replace( ' ', '_' ) );
        file.MoveTo( new_path );
    }
    

    • Marked as answer by xanrer Thursday, January 24, 2019 10:12 PM
    Thursday, January 24, 2019 8:01 PM
  • Check this:

    DirectoryInfo directory = new DirectoryInfo( scLoc );
    FileInfo[] files = directory.GetFiles();
    
    foreach( var file in files )
    {
        var new_path = Path.Combine( directory.FullName, file.Name.Replace( ' ', '_' ) );
        file.MoveTo( new_path );
    }

    Works like wonders! Thank you once again Viorel_! Just added the (.toLower()) part after the (Replace(' ', '_'))

    • Edited by xanrer Thursday, January 24, 2019 10:16 PM
    Thursday, January 24, 2019 10:16 PM