我想将文件复制到此应用程序的目录中。唯一的问题是它需要与它来自的目录中的文件类型相同。在这段代码中,我必须将文件类型放在名称后面。当我将文件复制到第二个目录时,它会自动变为.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;
}
}
}
}
答案 0 :(得分: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";
}
希望这有帮助!
答案 1 :(得分: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);