【问题标题】:Change extensions of all files in a directory更改目录中所有文件的扩展名
【发布时间】:2013-03-25 11:34:46
【问题描述】:

我没有收到错误,但扩展名没有更改。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string filename;
            string[] filePaths = Directory.GetFiles(@"c:\Users\Desktop\test\");
            Console.WriteLine("Directory consists of " + filePaths.Length + " files.");
            foreach(string myfile in filePaths)
                filename = Path.ChangeExtension(myfile, ".txt");
            Console.ReadLine();
        }
    }
}

【问题讨论】:

  • 看看能不能执行简单的DOS命令ren *.* *.txt,否则可以使用File.Move

标签: c# directory filenames


【解决方案1】:

Path.ChangeExtension 只返回一个带有新扩展名的字符串,它不会重命名文件本身。

您需要使用System.IO.File.Move(oldName, newName) 重命名实际文件,如下所示:

foreach (string myfile in filePaths)
{
    filename = Path.ChangeExtension(myfile, ".txt");
    System.IO.File.Move(myfile, filename);
}

【讨论】:

    【解决方案2】:

    Ì如果您想更改文件的扩展名,请致电File.Move()

    【讨论】:

      【解决方案3】:

      这只会改变路径的扩展名而不是文件的扩展名。

      原因:因为 ChangeExtension 被称为 Path.ChangeExtension。对于文件,使用System.IO. File 类及其方法。

      【讨论】:

        【解决方案4】:

        ChangeExtension 方法的 documentation 表示:

        更改路径字符串的扩展名。

        它并没有说它改变了文件的扩展名。

        【讨论】:

          【解决方案5】:

          我认为这是大致等效(正确)的代码:

                  DirectoryInfo di = new DirectoryInfo(@"c:\Users\Desktop\test\");
                  foreach (FileInfo fi in di.GetFiles())
                  {
                      fi.MoveTo(fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length - 1) + ".txt"); // "test.bat" 8 - 3 - 1 = 4 "test" + ".txt" = "test.txt"
                  }
                  Console.WriteLine("Directory consists of " + di.GetFiles().Length + " files.");
                  Console.ReadLine();
          

          【讨论】:

            猜你喜欢
            • 2013-01-30
            • 2012-05-29
            • 1970-01-01
            • 2017-09-10
            • 2015-06-12
            • 1970-01-01
            • 2023-03-12
            • 2018-08-12
            • 2012-02-24
            相关资源
            最近更新 更多