-4

我想使用此应用程序将文件复制到目录。唯一的问题是它需要与它来自的目录中的文件类型相同。在这段代码中,我必须将文件类型放在名称后面。当我将文件复制到第二个目录时,它会自动变成一个 .txt。我想要与第一个目录中相同的扩展名。我该怎么做呢?这是我的代码:

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Transfer_Click(object sender, EventArgs e)
    {
        File.Copy(@""+textBox1.Text, @""+textBox2.Text+"/"+ textBox3.Text);
        label2.Text = "File Transfer Succeeded";
    }

    private void Filesource_Click(object sender, EventArgs e)
    {
        DialogResult resDialog = openFileDialog1.ShowDialog();
        if (resDialog.ToString() == "OK")
        {
            textBox1.Text = openFileDialog1.FileName;
        }
    }

    private void Target_Click(object sender, EventArgs e)
    {
        DialogResult resDialog = folderBrowserDialog1.ShowDialog();
        if (resDialog.ToString() == "OK")
        {
            textBox2.Text = folderBrowserDialog1.SelectedPath;
        }
    }
}
}
4

2 回答 2

2

我认为你想这样做:

private void Transfer_Click(object sender, EventArgs e)
    {
        File.Copy(textBox1.Text, Path.Combine(textBox2.Text, Path.ChangeExtension(textBox3.Text, Path.GetExtension(textBox1.Text)));
        label2.Text = "File Transfer Succeeded";
    }

希望这可以帮助!

于 2013-06-10T10:09:34.303 回答
1
string sourcePath = @"c:\myDocument.docx";
            string targetPath = @"c:\xyzHello.crazyextension";
            string sourceExtension = Path.GetExtension(sourcePath);
            if (sourceExtension != Path.GetExtension(targetPath))
                targetPath = Path.ChangeExtension(targetPath, sourceExtension);
            File.Copy(sourcePath, targetPath);
于 2013-06-10T10:08:14.070 回答