How to duplicate a copy of a file selected in an 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 above code, I am looking at a file to open. I want to do this, find the file, select it and then click ok. When I click ok, I want to make a copy of the seleted file and provide the .txt extension with this duplicate file. I need help in achieving this.

thanks

+4
source share
3 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 the code will copy the selected file as txt with the same name and in the same directory.

if you need to overwrite an existing file with the same name, add one more parameter to the Copy method as true.

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

+8
source

You are using File.Copy as shown below

 File.Copy(openFileDialogCSV.FileName., openFileDialogCSV.FileName + ".txt"); 
+1
source

try it

 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(); System.IO.File.Copy(this.txtFileToImport.Text,"C://123.txt") } } 

123 can be changed with any file name you want.

0
source

All Articles