【问题标题】:C# Change current FileInfo file?C# 更改当前的 FileInfo 文件?
【发布时间】:2013-12-15 18:46:19
【问题描述】:

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

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

myFile.ChangeFile("myfile2.txt");

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

【问题讨论】:

    标签: c# fileinfo


    【解决方案1】:

    你不能那样做。文件名是在构建时指定的,以后不能更改。

    【讨论】:

    • 谢谢!好的,那我就做一个数组
    • @Half_Baked 你应该考虑DirectoryInfo.GetFiles()
    【解决方案2】:

    你不能在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++;
        }
    }
    

    【讨论】:

    • @Half_Baked 说他想对文件进行迭代,并愿意制作一个数组。这不是关于重命名,而是 Half_Baked 想要重用相同的 FileInfo 来检查各种文件。
    • @JulieShannon 谢谢你的代码,但我想我只会创建一个独特的 FileInfo 对象数组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多