C#更改当前的FileInfo文件?

时间:2013-12-15 18:46:19

标签: c# fileinfo

我想更改FileInfo对象当前使用的文件。假设我想遍历1000个文件。

FileInfo myFile = new FileInfo("myfile.txt");

myFile.ChangeFile("myfile2.txt");

我该怎么做?希望.FileName =,但它只是readonly。

2 个答案:

答案 0 :(得分:1)

你做不到。文件名在构造时指定,以后不能更改。

答案 1 :(得分:0)

你不能在c#中做到这一点你没有内置函数而是使用这个函数

 private void ChangeFiles(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++;
    }
}