Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a duplicate copy of the file selected in the OpenFileDialog control

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

    }

In the code above, i browse for a file to open. What I want to do is, browse for a file, select it and then press ok. On clicking ok, i want to make a copy of the seleted file and give that duplicate file a .txt extension. I need help on achieving this.

Thanks

like image 372
StackTrace Avatar asked Jan 16 '23 08:01

StackTrace


1 Answers

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

Above code will copy selected file as txt with same name and in to same directory.

if you need to overwrite existing file with same name add another parameter to Copy method as true.

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

like image 121
Damith Avatar answered Jan 18 '23 23:01

Damith