user188825
user188825

Reputation:

File operations

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

Upvotes: 0

Views: 340

Answers (4)

Nisus
Nisus

Reputation: 824

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);
        }
    }
}

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064114

Fundamentally, this is:

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

Upvotes: 1

Mohamed Mansour
Mohamed Mansour

Reputation: 40199

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).

Upvotes: 2

scottm
scottm

Reputation: 28699

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");

Upvotes: 0

Related Questions