如何制作在OpenFileDialog控件中选择的文件的副本

Sta*_*ace 4 c# openfiledialog winforms

// Browses file with OpenFileDialog control

    private void btnFileOpen_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialogCSV = new OpenFileDialog();

        openFileDialogCSV.InitialDirectory = Application.ExecutablePath.ToString();
        openFileDialogCSV.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
        openFileDialogCSV.FilterIndex = 1;
        openFileDialogCSV.RestoreDirectory = true;

        if (openFileDialogCSV.ShowDialog() == DialogResult.OK)
        {
            this.txtFileToImport.Text = openFileDialogCSV.FileName.ToString();
        }

    }
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我浏览要打开的文件.我想要做的是,浏览文件,选择它,然后按确定.单击确定后,我想复制选择的文件,并为该重复文件提供.txt扩展名.我需要帮助才能实现这一目标.

谢谢

Dam*_*ith 8

if (openFileDialogCSV.ShowDialog() == DialogResult.OK)
{
    var fileName = openFileDialogCSV.FileName;
    System.IO.File.Copy( fileName ,Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName)+".txt"));
}
Run Code Online (Sandbox Code Playgroud)

上面的代码会将所选文件复制为具有相同名称的txt并放在同一目录中.

如果需要覆盖具有相同名称的现有文件,请将另一个参数添加到Copy方法为true.

System.IO.File.Copy(source, destination, true);