我如何重命名一个文件使用c# ?
当前回答
private static void Rename_File(string FileFullPath, string NewName) // nes name without directory actualy you can simply rename with fileinfo.MoveTo(Fullpathwithnameandextension);
{
FileInfo fileInfo = new FileInfo(FileFullPath);
string DirectoryRoot = Directory.GetParent(FileFullPath).FullName;
string filecreator = FileFullPath.Substring(DirectoryRoot.Length,FileFullPath.Length-DirectoryRoot.Length);
filecreator = DirectoryRoot + NewName;
try
{
fileInfo.MoveTo(filecreator);
}
catch(Exception ex)
{
Console.WriteLine(filecreator);
Console.WriteLine(ex.Message);
Console.ReadKey();
}
enter code here
// string FileDirectory = Directory.GetDirectoryRoot()
}
其他回答
看一下System.IO.File。移动,“移动”文件到一个新名称。
System.IO.File.Move("oldfilename", "newfilename");
在文件中。方法,这将不会覆盖文件,如果它已经存在。它会抛出一个异常。
所以我们需要检查文件是否存在。
/* 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
或者用try catch将其包围以避免异常。
Move是做同样的=复制和删除旧的。
File.Move(@"C:\ScanPDF\Test.pdf", @"C:\BackupPDF\" + string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.pdf", DateTime.Now));
System.IO.File.Move(oldNameFullPath, newNameFullPath);
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);
}
}