You can use File.Move to do it.
public static class ImageRename
{
public static void ApplyChanges(string fileUrl,
string temporaryImageName,
string permanentImageName)
{
var currentFileName = Path.Combine(fileUrl,
temporaryImageName);
if (!File.Exists(currentFileName))
throw new FileNotFoundException();
var extention = Path.GetExtension(temporaryImageName);
var newFileName = Path.Combine(fileUrl,
$"{permanentImageName}
{extention}");
if (File.Exists(newFileName))
File.Delete(newFileName);
File.Move(currentFileName, newFileName);
}
}
When C# doesn't have some feature, I use C++ or C:
public partial class Program
{
[DllImport("msvcrt", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int rename(
[MarshalAs(UnmanagedType.LPStr)]
string oldpath,
[MarshalAs(UnmanagedType.LPStr)]
string newpath);
static void FileRename()
{
while (true)
{
Console.Clear();
Console.Write("Enter a folder name: ");
string dir = Console.ReadLine().Trim('\\') + "\\";
if (string.IsNullOrWhiteSpace(dir))
break;
if (!Directory.Exists(dir))
{
Console.WriteLine("{0} does not exist", dir);
continue;
}
string[] files = Directory.GetFiles(dir, "*.mp3");
for (int i = 0; i < files.Length; i++)
{
string oldName = Path.GetFileName(files[i]);
int pos = oldName.IndexOfAny(new char[] { '0', '1', '2' });
if (pos == 0)
continue;
string newName = oldName.Substring(pos);
int res = rename(files[i], dir + newName);
}
}
Console.WriteLine("\n\t\tPress any key to go to main menu\n");
Console.ReadKey(true);
}
}
In the File.Move method, this won't overwrite the file if it is already exists. And it will throw an exception.
So we need to check whether the file exists or not.
/* Delete the file if exists, else no exception thrown. */
File.Delete(newFileName); // Delete the existing file if exists
File.Move(oldFileName,newFileName); // Rename the oldFileName into newFileName
Or surround it with a try catch to avoid an exception.
First solution
Avoid System.IO.File.Move
solutions posted here (marked answer included).
It fails over networks. However, copy/delete pattern works locally and over networks. Follow one of the move solutions, but replace it with Copy instead. Then use File.Delete to delete the original file.
You can create a Rename method to simplify it.
Ease of use
Use the VB assembly in C#. Add reference to Microsoft.VisualBasic
Then to rename the file:
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(myfile, newName);
Both are strings. Note that myfile has the full path. newName does not. For example:
a = "C:\whatever\a.txt";
b = "b.txt";
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(a, b);
The C:\whatever\
folder will now contain b.txt
.
You can copy it as a new file and then delete the old one using the System.IO.File
class:
if (File.Exists(oldName))
{
File.Copy(oldName, newName, true);
File.Delete(oldName);
}