2016-12-14 11 views
-3

"_Copy"を追加してファイルの名前を変更するファイルコピーを作成するように求められましたが、ファイルの種類は保持されます。例えばファイルをコピーして名前を変更します

:へ

c:\...mike.jpg 

:ここ

c:\...mike_Copy.jpg 

が私のコードです:

private void btnChseFile_Click(object sender, EventArgs e) 
{ 
    prgrssBar.Minimum = 0; 
    OpenFileDialog ofd = new OpenFileDialog(); 
    ofd.Title = "Which file do you want to copy ?";    

    DialogResult fc = ofd.ShowDialog();      
    tbSource.Text = ofd.FileName; 
    tbDestination.Text = tbSource.Text + "_Copy";   
} 
+3

問題/エラーは何ですか? – RandomStranger

+0

@Bas comeonそれは明らかです。 'それは仕事なし' – Ivaro18

答えて

0

ヨuは、あなたがしようとしている思われるものを行うには、クラスSystem.IO.FileInfoSystem.IO.Pathを使用することができます。

OpenFileDialog od = new OpenFileDialog(); 
if(od.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
{ 
    System.IO.FileInfo fi = new System.IO.FileInfo(od.FileName); 
    string oldFile = fi.FullName; 

    string newFile = oldFile.Replace(System.IO.Path.GetFileNameWithoutExtension(oldFile), 
     string.Format("{0}_Copy", 
      System.IO.Path.GetFileNameWithoutExtension(oldFile))); 
    MessageBox.Show(newFile); 
} 

次に、あなたがコピーを実行するには、次を呼び出すことができます。

System.IO.File.Copy(oldFile, newFile); 
0

あなたが前に、ファイル名の末尾に_Copyを追加していません拡張。あなたは拡張子の前にそれを追加する必要があります。

string destFileName = $"{Path.GetFileNameWithoutExtension(ofd.FileName)}_Copy{Path.GetExtension(ofd.FileName)}"; 

やC#6なし:

string destFileName = String.Format("{0}_Copy{1}", 
            Path.GetFileNameWithoutExtension(ofd.FileName), 
            Path.GetExtension(ofd.FileName)); 

次に、ファイルの使用へのフルパスを取得するには:

string fullPath = Path.Combine(Path.GetDirectoryName(ofd.FileName, destFileName)); 

次に実行します実際のコピーだけを使用してください:

File.Copy(ofd.FileName, fullPath); 
関連する問題