Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to copy a text file from one location to another without overwrite existing file and it should be renamed to different file name when we copy it to another location like file1.txt, file2.txt... Plz tell me how to do it. I am using windows application c#.net. Thanx in advance...
Posted
Comments
[no name] 29-Jun-13 5:27am    
File.Copy(string sourceFileName, string destFileName)
BillWoodruff 30-Jun-13 16:52pm    
@Member 9781851: Quit messing around, and study the excellent code examples OriginalGriff has posted here. Edit your original post to reflect exactly what your current Windows Application is, and exactly what you want to do.

First, check if the file exists - that's trivial:
C#
if (File.Exists(path))
   {
   ...
   }
Finding the next free number is more complex:
C#
    ...
    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:
C#
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);
    }

/// <summary>
/// Find the number at the end of the string
/// </summary>
private Regex fileNumber = new Regex("\\d+$", RegexOptions.Compiled);
/// <summary>
/// Get the next free file number given a base file name
/// </summary>
/// <param name="path">Path to base file</param>
/// <returns>Path to free file name</returns>
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);
    }
/// <summary>
/// Get the number (if any) at the end of a filename
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
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...
 
Share this answer
 
v2
Comments
Pankaj Mahor 29-Jun-13 6:43am    
I already have a file and i am using two textboxes one to get source file and second to place file on a destination folder. I cant understand your code. Plz give any other solution.
OriginalGriff 29-Jun-13 7:10am    
You need to check if the source file exists in the destination: so use File.Exists. If it doesn't, then you can just copy it over.
If it does, then the way I would do it is to rename the file of the same name to filen and then copy the source file over.
So, if the source is called myFile.txt:
If destination has no file called myFile.txt, then just copy it over.
Other wise, find the highest numbered file called myFilenn.txt. For example, if the destination folder contained:
myFile.txt
myFile1.txt
myFile2.txt
...
myFile76.txt
it would mean finding the file called "myFile76.txt" and renaming "myFile.txt" to "myFile77.txt" then copying the source file over.
This way, the latest version always has the same name as the source and is easy to find.
There is an explanation of how this code works in a Tip I wrote this morning:
http://www.codeproject.com/Tips/613449/Finding-a-free-file-name-and-number-combination
Pankaj Mahor 29-Jun-13 10:18am    
Here is the link that describe what i want to do but problem is i am getting error on fileupload stament-
http://naspinski.net/post/Saving-multiple-files-of-the-same-name.aspx
OriginalGriff 30-Jun-13 4:22am    
Hang on a moment - "fileupload stament"? You said this is a Windows Application - why are you trying to use FileUpload controls in a Win App?
Pankaj Mahor 30-Jun-13 0:04am    
Plz reply.
Hello,

Please have a look this[^] MSDN Documentation. You will basically be using File.Copy API. As far as finding the unique name in the destination is concerned you can use code similar to one shown below
C#
public string getDestFile(string srcFile, string destDir) {
    int cntr = 1;

    int pos = strFile.LastIndexOf(".");
    string fName = srcFile.SubString(0, pos - 1);
    string strExt = srcFile.SubString(pos + 1);
    string destName = fName + "-" + cntr + "." + strExt;
    while (!File.Exists(Path.Combine(new String[] {destDir, destPath}))) {
        cntr++;
        destName = fName + "-" + cntr + "." + strExt;
    }
    return destName;
}

Regards,
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900