简体   繁体   中英

Change extensions of all files in a directory

I don't get an error, but the extension isn't changed.

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();
        }
    }
}

Path.ChangeExtension only returns a string with the new extension, it doesn't rename the file itself.

You need to use System.IO.File.Move(oldName, newName) to rename the actual file, something like this:

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

如果要更改文件的扩展名,请调用File.Move()

This only changes extension of path and not of file.

Reason: Since ChangeExtension is called of Path.ChangeExtension . For file, use System.IO. File System.IO. File Class and its methods.

The documentation for method ChangeExtension says that:

Changes the extension of a path string.

It doesn't say that it changes extension for a file.

I think this is roughly equivalent (correct) code:

        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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM