我需要互相交换2个文件C#

时间:2013-05-14 13:06:48

标签: c#

我正在尝试互相交换2个文件。我正在尝试这样做,但它无法正常工作。文件正在替换但备份文件未创建。你有其他解决方案吗?

File.Replace(newLocation,defualtSource, newLocation);

3 个答案:

答案 0 :(得分:3)

File.Move("file1.txt", "temp.txt");
File.Move("file2.txt", "file1.txt");
File.Move("temp.txt", "file2.txt");

为什么替换不起作用,但是,我没有得到。你确定你正在使用它吗?

答案 1 :(得分:2)

File.Replace的第三个参数是备份文件的路径。您确定要将正确的参数传递给Replace方法吗?

请参阅http://msdn.microsoft.com/en-us/library/9d9h163f.aspx上的示例,了解要传递的参数示例。

答案 2 :(得分:1)

如果要交换2个文件,请检查此示例:

        const string file1Folder = "D:\\File1";
        const string file1 = "file1.txt";
        const string file2Folder = "D:\\File2";
        const string file2 = "file2.txt";

        var file1Filename = Path.Combine(file1Folder, file1);
        var file1Destination = Path.Combine(file2Folder, file1);

        var file2Filename = Path.Combine(file2Folder, file2);
        var file2Destination = Path.Combine(file1Folder, file2);

        File.Move(file1Filename, file1Destination);
        File.Move(file2Filename, file2Destination);

如果您只想交换两个文件的文本,可以使用File.Replace,请检查示例here

相关问题