-3

I was asked to make a file copier that will change the name of a file, by adding "_Copy", but will keep the type of file.

For example:

c:\...mike.jpg

to:

c:\...mike_Copy.jpg

Here is my code:

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";          
}
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
Elad Tzabari
  • 37
  • 1
  • 4

2 Answers2

2

You can use the classes System.IO.FileInfo and System.IO.Path to do what it appears you are attempting:

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

Then you can call the following to perform the copy:

System.IO.File.Copy(oldFile, newFile);
gmiley
  • 6,531
  • 1
  • 13
  • 25
0

You are appending the _Copy onto the end of the filename and not before the extension. You need to add it before the extension:

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

Or without C# 6:

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

Then to get the full path to the file use:

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

Then to perform the actual copy just use:

File.Copy(ofd.FileName, fullPath);
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69