0

I have in project one folder for uploaded files, I want to check if in this folder exist files contains some text in title. I want to rename the file if it contains text "test"

For example, in folder "/uploadedFiles/" I have 4 files: test_01.jpg, 02.jpg, 03.png, test_04.txt

I want to rename the files: "test_01.jpg" to "01.jpg" and "test_04.txt" to "04.txt"

I can edit the files like this:

System.IO.File.Move("test_01.jpg", "test_01.jpg".Replace("test_",""));

I need to get list of files that contains "test" in title from this folder

Alex
  • 8,908
  • 28
  • 103
  • 157
  • http://stackoverflow.com/questions/3775828/get-files-from-directory-with-pattern, http://stackoverflow.com/questions/10893311/find-files-with-matching-patterns-in-a-directory-c, http://stackoverflow.com/questions/2700039/how-to-collect-all-files-in-a-folder-and-its-subfolders-that-match-a-string, http://stackoverflow.com/questions/3218910/rename-a-file-in-c-sharp. Please try to use the search, show what you have tried and explain where specifically yhou need help. – CodeCaster Nov 20 '14 at 11:31

4 Answers4

2

You can get the list files that contain test in their name:

var files = Directory.EnumerateFiles(folderPath, "*test*.*");

Also you can use regex to do this:

Regex reg = new Regex(@".*test.*\..*",RegexOptions.IgnoreCase);

var files = Directory.GetFiles(yourPath, "*.*")
                     .Where(path => reg.IsMatch(path))
                     .ToList();
Ali Sepehri.Kh
  • 2,468
  • 2
  • 18
  • 27
1
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(folderPathToUploadedFiles);

IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

IEnumerable<System.IO.FileInfo> fullfileinfo =(from file in fileList  where file.Name.Contains("test") select file);
Abbas Galiyakotwala
  • 2,949
  • 4
  • 19
  • 34
1

This will get you a list of matching files, and then move each one:

foreach (var file in Directory.EnumerateFiles("somePath", "test_*"))
{
    var newFileName = Path.GetFileName(file).Remove(0, 5);  // removes "test_"

    File.Move(file, Path.Combine(Path.GetDirectoryName(file), newFileName));
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
1

this code renames all files with the keyword "test_". it is NOT case sensitive due to the "ToLower()" call

        const string testKeyword = "test_";
        var testFilePaths = Directory.GetFiles(@"c:\tmp").Where(f => f.ToLower().Contains(testKeyword.ToLower()));
        foreach (var testFilePath in testFilePaths)
        {
            File.Move(testFilePath, testFilePath.Replace(testKeyword, string.Empty));
        }
Matthias
  • 1,267
  • 1
  • 15
  • 27