Hello kana250688,
First you need to save the file in diffrent name and delete the old one.
Please refer the below codes.
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<string, string> files = new Dictionary<string, string>();
files.Add("Sample.docx", "Sample.docx");
files.Add("Sample.pdf", "Sample.pdf");
files.Add("Sample.xlsx", "Sample.xlsx");
RenameFiles(files, Server.MapPath("~/Files"));
}
private void RenameFiles(Dictionary<string, string> fileNameMapper, string path)
{
DirectoryInfo dir = new DirectoryInfo(path);
IEnumerable<FileInfo> files = dir.EnumerateFiles().Where(fi => fileNameMapper.ContainsKey(fi.Name));
foreach (FileInfo file in files)
{
string oldPath = Path.Combine(file.Directory.FullName, fileNameMapper[file.Name]);
string newPath = Path.Combine(file.Directory.FullName, (DateTime.Now.Ticks + "_" + fileNameMapper[file.Name]));
if (File.Exists(oldPath))
{
file.MoveTo(newPath);
File.Delete(oldPath);
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs)
Dim files As Dictionary(Of String, String) = New Dictionary(Of String, String)()
files.Add("Sample.docx", "Sample.docx")
files.Add("Sample.pdf", "Sample.pdf")
files.Add("Sample.xlsx", "Sample.xlsx")
RenameFiles(files, Server.MapPath("~/Files"))
End Sub
Private Sub RenameFiles(fileNameMapper As Dictionary(Of String, String), path As String)
Dim dir As DirectoryInfo = New DirectoryInfo(path)
Dim files As IEnumerable(Of FileInfo) = dir.EnumerateFiles().Where(Function(fi) fileNameMapper.ContainsKey(fi.Name))
For Each file As FileInfo In files
Dim oldPath As String = IO.Path.Combine(file.Directory.FullName, fileNameMapper(file.Name))
Dim newPath As String = IO.Path.Combine(file.Directory.FullName, (DateTime.Now.Ticks & "_" + fileNameMapper(file.Name)))
If IO.File.Exists(oldPath) Then
file.MoveTo(newPath)
IO.File.Delete(oldPath)
End If
Next
End Sub
Screenshot