2012-06-21 102 views
4
// 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(); 
     } 

    } 

在上面的代碼中,我瀏覽了一個要打開的文件。我想要做的是,瀏覽文件,選擇它,然後按確定。點擊確定後,我想製作一個選擇文件的副本,併爲該副本文件添加一個.txt擴展名。我需要幫助來實現這一點。如何在OpenFileDialog控件中選擇文件的副本副本

感謝

回答

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

上面的代碼將複製所選文件具有相同名稱的TXT和到同一目錄中。

如果您需要使用相同名稱覆蓋現有文件,請將另一個參數添加到Copy方法爲true。

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

+0

這個作品,謝謝 – StackTrace

1

您使用File.Copy如下,

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

哪裏得到這個錯誤?哪一行? –

0

試試這個

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可以通過任何你想要的文件名進行更改。