Drive recursive cycle and replace illegal characters

I need to create an application that drills to a specific drive, reads all file names and replaces illegal SharePoint characters with underscores. The illegal symbols that I mean are:~ # % & * {} / \ | : <> ? - ""

Can someone provide a link to the code or the code itself on how to do this? I am VERY new to C # and I need all the help I can get. I examined the code when recursively drilling through a disk, but I'm not sure how to replace a character and a recursive loop. Please, help!

+3
source share
4 answers

A tip for removing illegal characters is here:

?

, .

, ,

var files = System.IO.Directory.EnumerateFiles(currentPath);

foreach (string file in files)
{
    System.IO.File.Move(file, ConvertFileName(file));
}

ConvertFileName, , , , .

, .NET 3.5, GetFiles(). MSDN:

GetFiles : EnumerateFiles, ; GetFiles, , . , , EnumerateFiles .


string path = @"c:\dev";
string searchPattern = "*.*";

string[] dirNameArray = Directory.GetDirectories(path, searchPattern, SearchOption.AllDirectories);

// Or, for better performance:
// (but breaks if you don't have access to a sub directory; see 2nd link below)
IEnumerable<string> dirNameEnumeration = Directory.EnumerateDirectories(path, searchPattern, SearchOption.AllDirectories);
+6

, :

, : /\:*?"<>|.

, . , My~Project.doc My#Project.doc My_Project.doc.

+6

- , . , .

private void SharePointSanitize(string _folder)
{
    // Process files in the directory
    string [] files = Directory.GetFiles(_folder);
    foreach(string fileName in files)
    {
        File.Move(fileName, SharePointRename(fileName));
    }
    string[] folders = Directory.GetDirectories(_folder);
    foreach(string folderName in folders)
    {
        SharePointSanitize(folderName);
    }
}

private string SharePointRename(string _name)
{
    string newName = _name;
    newName = newName.Replace('~', '');
    newName = newName.Replace('#', '');
    newName = newName.Replace('%', '');
    newName = newName.Replace('&', '');
    newName = newName.Replace('*', '');
    newName = newName.Replace('{', '');
    newName = newName.Replace('}', '');
    // .. and so on
    return newName;
}

:

  • '' SharePointRename() , , , .
  • , , ~ %
+2
class Program
{
    private static Regex _pattern = new Regex("[~#%&*{}/\\|:<>?\"-]+");
    static void Main(string[] args)
    {
        DirectoryInfo di = new DirectoryInfo("C:\\");
        RecursivelyRenameFilesIn(di);
    }

    public static void RecursivelyRenameFilesIn(DirectoryInfo root)
    {
        foreach (FileInfo fi in root.GetFiles())
            if (_pattern.IsMatch(fi.Name))
                fi.MoveTo(string.Format("{0}\\{1}", fi.Directory.FullName, Regex.Replace(fi.Name, _pattern.ToString(), "_")));

        foreach (DirectoryInfo di in root.GetDirectories())
            RecursivelyRenameFilesIn(di);
    }
}

, .

+1

Source: https://habr.com/ru/post/1746016/


All Articles