如何删除文件夹c#

时间:2017-02-20 10:42:56

标签: c# file

我有一个包含大量图片的文件夹,所有图片都具有相同的名称格式:

some-random-name-min.jpg
another-random-name-min.jpg
and-another-random-name-min.jpg

我想去掉最后一个-min 在这里,我做了一个脚本来更改所有文件的名称,但我只想删除最后四个字符。

private void Rename(string fPath, string fNewName)
{
    string fExt;
    string fFromName;
    string fToName;
    int i = 1;

    //copy all files from fPath to files array
    FileInfo[] files = new DirectoryInfo(fPath).GetFiles();
    //loop through all files
    foreach (var f in files)
    {
        //get the filename without the extension
        fFromName = Path.GetFileNameWithoutExtension(f.Name);
        //get the file extension
        fExt = Path.GetExtension(f.Name);

        //set fFromName to the path + name of the existing file
        fFromName = string.Format(@"{0}\{1}", fPath, f.Name);
        //set the fToName as path + new name + _i + file extension
        fToName = string.Format(@"{0}\{1}_{2}{3}", fPath, fNewName, i.ToString(), fExt);

        //rename the file by moving to the same place and renaming
        File.Move(fFromName, fToName);
        //increment i
        i++;
    }
}

1 个答案:

答案 0 :(得分:0)

private string Remove4LastCharacter(string fName)
{
    string nameWithoutExt = Path.GetFileNameWithoutExtension(fName);
    // Length is less than or equal 4 => I can not remove them
    if (nameWithoutExt.Length <= 4)
    {
        return fName;
    }

    // Other cases
    string newNameWithoutExt = nameWithoutExt.Substring(0, nameWithoutExt.Length - 4);
    return newNameWithoutExt + Path.GetExtension(fName);
}

申请代码:

// Use Path.Combine instead
fFromName = Path.Combine(fPath, f.Name);
fNewName = Remove4LastCharacter(f.Name);
fToName = string.Format("{0}_{1}{2}", Path.Combine(fPath, fNewName), i.ToString(), fExt);