First, check if the file exists - that's trivial:
if (File.Exists(path))
{
...
}
Finding the next free number is more complex:
...
string path = @"D:\Temp\myPic.jpg";
string pathOnly = path.Substring(0, path.LastIndexOf('\\'));
string[] files = Directory.GetFiles(pathOnly, Path.GetFileNameWithoutExtension(path) + "*" + Path.GetExtension(path));
int x = files.Max(f => GetFileNumber(f));
...
private Regex fileNumber = new Regex("\\d+$");
private int GetFileNumber(string file)
{
Match m = fileNumber.Match(Path.GetFileNameWithoutExtension(file));
if (!m.Success) return 0;
return int.Parse(m.Value);
}
You can then use File.Move to rename the file!
"Ok, i have checked that link and its so complicated code. Can you plz give me any other code to do it easily? I need to rename file and add number to filename like mytext1.txt, mytext2.txt. Plz help."
That isn't complicated at all! :laugh:
If you're a beginner, then in future please say - it allows us to talk differently to you, allowing for your lack of experience.
The code is pretty simple, the only complicated parts are the Regex (if you haven't met them, they are just string "find and replace" on steroids!) and the line using the Linq Max extension and a lambda expression - just ignore them both for the moment.
If you treat the code as a "black box" method you can call from your code, then it's pretty simple to do what you want: just call the method GetFreeFileNumber with the path to where you want to save the file.
The whole code is not complex:
private void Mybutton_Click(object sender, EventArgs e)
{
string newFile = @"D:\MyPic.jpg";
string destName = @"D:\Temp\MyPic.jpg";
if (File.Exists(destName))
{
string destNameWithNumber = GetFreeFileNumber(destName);
File.Move(destName, destNameWithNumber);
}
File.Copy(newFile, destName);
}
private Regex fileNumber = new Regex("\\d+$", RegexOptions.Compiled);
private string GetFreeFileNumber(string path)
{
string pathOnly = path.Substring(0, path.LastIndexOf('\\') + 1);
string nameOnly = Path.GetFileNameWithoutExtension(path);
string extOnly = Path.GetExtension(path);
string[] files = Directory.GetFiles(pathOnly, nameOnly + "*" + extOnly);
int largest = files.Max(f => GetFileNumber(f));
return string.Format("{0}{1}{2}{3}", pathOnly, nameOnly, largest + 1, extOnly);
}
private int GetFileNumber(string file)
{
Match m = fileNumber.Match(Path.GetFileNameWithoutExtension(file));
if (!m.Success) return 0;
return int.Parse(m.Value);
}
To copy D:\MyPic.jpg to D:\Temp\ with numeric backups, that's all you have to do...