文件操作

时间:2009-10-13 03:56:19

标签: c# file-io

我想将文件从一个文件夹移动到另一个(目标)文件夹。如果目标文件夹中已存在相同的文件,我想重命名.how在C#中实现。

提前致谢 谢卡尔

4 个答案:

答案 0 :(得分:2)

System.IO.File。* 拥有您需要的一切。

System.IO.File.Exists =检查文件是否存在。 System.IO.File.Move =移动(或重命名文件)。

答案 1 :(得分:1)

从根本上说,这是:

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

答案 2 :(得分:0)

您需要使用System.IO.Fil e类并提前检查文件是否存在。

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

File.Move("myotherfile.txt","myfile.txt");

答案 3 :(得分:0)

如果您更喜欢Windows风格的行为,那么我正在使用这些操作的代码

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