2013-06-10 5 views
-4

Je veux copier un fichier dans un répertoire avec cette application. Le seul problème est qu'il doit être le même type de fichier que dans le répertoire d'origine. Dans ce code, je dois mettre le type de fichier derrière le nom. Lorsque je copie le fichier dans le 2ème répertoire, il devient automatiquement un fichier .txt. Je veux la même extension que dans le premier répertoire. Comment puis-je faire cela? Voici mon code:Copie de fichier avec C#. Filetype

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

Voir [FileInfo Class] (http://msdn.microsoft.com/fr-fr/library/system.io.fileinfo.aspx). – Codesleuth

+0

Aussi, au lieu de concaténer des chaînes comme vous êtes, utilisez 'Path.Combine (textBox2.Text, textBox3.Text)'. –

+0

Juste intéressant - quel est l'avantage de le faire '@" "+ textBox1.Text'? –

Répondre

2

Je pense que vous voulez faire ceci:

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"; 
    } 

Hope this helps!

+0

Merci beaucoup. Cela a fonctionné: D – Loko

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);