使用循环

时间:2016-11-18 13:40:43

标签: c# file pdf file-rename

我必须更改一些pdf(1,2 TB)的名称。文件的名称例如是20160112_0(年/月/日/ _0)。我必须将文件名更改为tu,2016年1月12日(工作日/日/月/年)。

我已经获得了文件名,但我不知道如何更改它。

string dir = @"path";
        string[] files = Directory.GetFiles(dir);
        foreach (string file in files)
            Console.WriteLine(Path.GetFileName(file));

3 个答案:

答案 0 :(得分:1)

试试这个

        string dir = @"YourPath";
        string fileDate, new_fileDate;
        DateTime dt;
        foreach (string original_filename in Directory.GetFiles(dir))
        {
            fileDate = Path.GetFileName(original_filename).Substring(0, 8);
            dt = DateTime.ParseExact(fileDate, "yyyyMMdd", CultureInfo.InvariantCulture);
            new_fileDate = dt.ToString("ddd_dd_MMMM_yyyy");
            File.Move(original_filename, original_filename.Replace(fileDate, new_fileDate));
        }

答案 1 :(得分:1)

//from your code: 
DateTime fileDate;
var newFileName = newFileName(Path.GetFileName(file), out fileDate);
File.Move(newFileName);


string newFileName(string oldFileName, out DateTime fileDate)
    {

        var fileDate =  DateTime.ParseExact(oldFileName.Take(8),
                                            "yyyyMMdd",
                                            CultureInfo.InvariantCulture,
                                            DateTimeStyles.None) ;

    var nfn = fileDate.Day.ToString() + "." + fileDay.Month.ToString("MMM") + fileDay.Year.ToString("YYYY") + ".pdf";

    return nfn;

    }

答案 2 :(得分:0)

    string path = @"path";
    System.IO.DirectoryInfo dir = System.IO.DirectoryInfo(path);
    foreach System.IO.FileInfo file in dir.GetFiles()){
        string newname = GetNewName(file.Name);
if(newname!=file.Name)
        file.Move(file.FullName,  System.IO.Path.Combine(file.DiretoryName, newname);
    }

    public string GetNewName(string f){
       string without_ext = f.split('.').First();
    string result = f;
       Match m = Regex.Match(without_ext, "(\\d{4})(\\d[012]?)(\\d[0123]?\\d)")
        if(m.Success){
           result = $"{m.Groups[3].Value}.{CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(int.Parse(m.Groups[2].Value)} {m.Groups[1].Value).{f.split('.').Last()}}; 
       }
       return result;
    }