السلام عليكم,
هذة الدالة تقوم بتغير اسم الملف اذا وجد نفس الاسم, مع التكرار بأرقام ,مثل عملية التسمية بالويندوز.
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace AutoRename
{
public partial class frmMain : Form
{
public string SaveFile(string destFileName)
{
if(destFileName == null)
return null;
string dir = Path.GetDirectoryName(destFileName).EndsWith("\\")
? Path.GetDirectoryName(destFileName) : Path.GetDirectoryName(destFileName) + "\\";
string newDestFileName;
if(File.Exists(destFileName)) {
int Value = 1;
newDestFileName = dir + Path.GetFileNameWithoutExtension(destFileName) +
" (" + Value + ")" + Path.GetExtension(destFileName);
while(File.Exists(newDestFileName)) {
newDestFileName = dir + Path.GetFileNameWithoutExtension(destFileName) +
" (" + Value + ")" + Path.GetExtension(destFileName);
Value++;
}
return newDestFileName;
} else {
return destFileName;
}
}
private void btnMake_Click(object sender, EventArgs e)
{
File.CreateText(SaveFile(".\\myNewFile.txt"));
}
public frmMain()
{
InitializeComponent();
}
private Button btnCreateFile = new Button();
private void InitializeComponent()
{
//
// btnCreateFile
//
this.btnCreateFile.Location = new Point(50, 50);
this.btnCreateFile.Name = "btnCreateFile";
this.btnCreateFile.Size = new Size(200, 100);
this.btnCreateFile.Text = "Create New File";
this.btnCreateFile.UseVisualStyleBackColor = true;
this.btnCreateFile.Click += new EventHandler(this.btnMake_Click);
//
// frmMain
//
this.StartPosition = FormStartPosition.CenterScreen;
this.ClientSize = new Size(300, 200);
this.Controls.Add(this.btnCreateFile);
this.Name = "frmMain";
this.Text = "Auto Rename";
this.ResumeLayout(false);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new frmMain());
}
}
}