tags:

views:

89

answers:

4

Hi

I wanted move the file from one folder to another(target) folder.If the same file is already exist in target folder i wants to rename .how to implement in C#.

Thanks in advance Sekar

+1  A: 

Fundamentally, this is:

string source = ..., dest = ...; // the full paths
if(File.Exists(dest)) 
{
   File.Move(dest, Path.GetTempFileName());
}
File.Move(source, dest);
Marc Gravell
A: 

You'll want to use the System.IO.File class and check for the file's existence ahead of time.

if(File.Exists("myfile.txt"))
  File.Move("myfile.txt", "myfile.bak");

File.Move("myotherfile.txt","myfile.txt");
scottm
+2  A: 

System.IO.File.* has everything you need.

System.IO.File.Exists = To check if the file exists. System.IO.File.Move = To move (or rename a file).

Mohamed Mansour
A: 

If you prefer a windows-style behavior, so there is the code I'm using for such an operation

public static void FileMove(string src,ref string dest,bool overwrite)
{
    if (!File.Exists(src))
        throw new ArgumentException("src");
    File.SetAttributes(src,FileAttributes.Normal);
    string destinationDir = Path.GetDirectoryName(dest);
    if (!Directory.Exists(destinationDir))
    {
        Directory.CreateDirectory(destinationDir);
    }
    try
    {
        File.Move(src,dest);
    }
    catch (IOException)
    {
        //error # 183 - file already exists
        if (Marshal.GetLastWin32Error() != 183)
            throw;
        if (overwrite)
        {
            File.SetAttributes(dest,FileAttributes.Normal);
            File.Delete(dest);
            File.Move(src,dest);
        }
        else
        {
            string name = Path.GetFileNameWithoutExtension(dest);
            string ext = Path.GetExtension(dest);
            int i = 0;
            do
            {
                dest = Path.Combine(destinationDir,name
                    + ((int)i++).ToString("_Copy(#);_Copy(#);_Copy")
                    + ext);
            }
            while (File.Exists(dest));
            File.Move(src,dest);
        }
    }
}
Nisus