Standardizing file names in a folder

Viewed 124

Is there any function to standardize file names in a folder?

I'm developing a program in C # that needs to check if the filenames are spelled correctly and then move them to another folder.

For example I usually get a file like this 082018 - Name - Reason.txt, however some people forget to put the spacing or invert the values, I need to check the names and put them in the pattern above.

1 Answers

I think using a Regex for this situation would be ideal. You can write a simple function that would verify if the file name is in order, and even return each part of it.

Let's declare a class to hold your file name data in the following format.

public class FileNameFormat
{
    public string FileName { get; set; }
    public DateTime Date { get; set; }
    public string Name { get; set; }
    public string Reason { get; set; }
    public bool IsValid { get; set; }
}

Now a method like this would verify your file name, using the Regex provided.

public static FileNameFormat VerifyFileName(string fileName)
{
    var fileNameInfo = new FileNameFormat();
    fileNameInfo.FileName = fileName;

    var rgx = new Regex(@"^(\d{6}) - (.+) - (.+).txt$");
    var match = rgx.Match(fileName);
    fileNameInfo.IsValid = match.Success;
    if (DateTime.TryParseExact(match.Groups[1].Value, "MMddyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime result))
    {
        fileNameInfo.Date = result;
    }
    fileNameInfo.Name = match.Groups[2].Value;
    fileNameInfo.Reason = match.Groups[3].Value;

    return fileNameInfo;
}

The Regex assumes:

  • Date in your file name is of length 6, and are all numerical values.
  • All file names have the extension .txt.
  • Both Name and Reason sections are at least 1-character long.

Also, in the case that the Match is a success, even though I convert the value to a DateTime I'm not doing any additional verifications to see if it's in that format. For example, if the date is set in the format yyMMdd the Regex would still pass, but may not be the format you want (assuming the format you're using is MMddyy).

So this is really only a starting point but you can change your Regex and verifications based on your needs/constraints.

Related