Reputation: 22010
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();
}
}
}
Upvotes: 0
Views: 9896
Reputation: 4848
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();
Upvotes: 0
Reputation: 281835
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);
}
Upvotes: 14
Reputation: 16623
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.
Upvotes: 1
Reputation: 48600
This only changes extension of path and not of file.
Reason: Since ChangeExtension is called of Path.ChangeExtension
. For file, use System.IO. File
Class and its methods.
Upvotes: 1