0

I am looking for a way to move a file from one directory to another using C#. I have a forms application that I would like to have the user select a file using the file chooser and upon clicking the "Set Background" button have the file transferred to a location specified within the application.

Upon trying the answer provided by @VulgarBinary I am getting the following exception:

System.IO.IOException: Cannot create a file when that file already exists.

enter image description here

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
  • possible duplicate of [How to bring up the built-in File Copy dialog?](http://stackoverflow.com/questions/6687443/how-to-bring-up-the-built-in-file-copy-dialog) – John Alexiou May 12 '15 at 00:06
  • @ja72 - No, the OP isn't having an issue with the WinForms application, they're having an actual issue moving the file. – VulgarBinary May 12 '15 at 00:20
  • 1
    I **greatly disagree** with the too broad. The OP said they couldn't figure out how to move the file. Not how do I write a program, or how do I do a billion things, they asked **how do I move a file** it's 1 line of C#... Far cry from "too broad". The question has been edited, time to fix the off base flags. – VulgarBinary May 12 '15 at 01:03
  • @santiago - Thanks :-) I'm sure the OP appreciates it too. – VulgarBinary May 12 '15 at 02:01
  • The OP needs to show the current code used to do the copying. Maybe it is a matter of a flag setting in the file stream, or an issue with UAC. – John Alexiou May 12 '15 at 17:57
  • @ja72 - It's resolved. :-) Although I appreciate the insight and asking for additional clarification. Cheers! – VulgarBinary May 12 '15 at 20:42

2 Answers2

5

You will need to ensure your program has appropriate permissions to write the files but:

if (File.Exists(sourcePath))
{
   File.Move(sourcePath, destinationPath);
}

This should work to do what you are wanting to do.

Example:

var sourcePath = "C:\Users\someuser\Pictures\VulgarBinary.jpg";
var destinationPath = "C:\Whatever\Path\You\Want\VulgarBinary.jpg";

EDIT 1

Given your comments below this answer you are running into a problem where the file you are creating already exists. If you would like to replace this you can simple do:

if (File.Exists(sourcePath))
{
   if(File.Exists(destinationPath))
      File.Delete(destinationPath);
   File.Move(sourcePath, destinationPath);
}

If you don't care what the output file's name is and just always want to write it you can do something like:

var outputDirectory = "C:\\Whatever\\Path\\You\\Want\\";

if (File.Exists(sourcePath))
{
   File.Move(sourcePath, outputDirectory + Guid.NewGuid().ToString() + ".jpg");
}

The latter will always copy the file (all-be-it with a different name). The first solution will replace any file with the same name with your new file.

Cheers!

VulgarBinary
  • 3,520
  • 4
  • 20
  • 54
  • Didnt work. Got an unhandled exception "An unhandled exception of type "System.IO.IOException" occured in mscorlib.dll Additional information: Cannot create a file when that file already exists." http://gyazo.com/fe4fb456cb4512cb9916bfd5bd5452f8 – Admiral Kitteh May 11 '15 at 23:39
  • Run your forms app as an administrator. And please provide the exception details. If the exception is Unauthorized or something along those lines it means that as the executing user you do not have privileges to either read or write at the specified locations. To fix this you would need to specify that the program "run as" a different user. This is pretty boiler plate C#, so there is not much that can go wrong aside from lacking permissions. – VulgarBinary May 11 '15 at 23:40
  • OK. So you have a duplicate file, meaning you already created a file with the name you are trying to write. What you could do is something like my edit above. It provides two options, both of which would work, it just depends on what approach you want to take and desired outcome. – VulgarBinary May 12 '15 at 00:02
  • 1
    @Admiral, do not try to post code to a comment. Click [Edit](http://stackoverflow.com/posts/30178632/edit) and add the information to your question. – Dour High Arch May 12 '15 at 00:07
  • The only recent questions that I can see that you answered that were closed later were not closed as duplicates. One was closed as off-topic and the other as too-broad, was there a specific question that you thought needed to be reopened. – apaul May 12 '15 at 01:39
  • Just this one at the moment. I had a few last week squashed and the OP ended up deleting. I appreciate you following up @apaul34208 Sorry for losing my cool. – VulgarBinary May 12 '15 at 01:47
  • This one wasn't closed as a duplicate and looking at the comments here I can see how some could view it as being a little too broad. – apaul May 12 '15 at 01:50
  • 1
    This may help: http://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/ – apaul May 12 '15 at 01:50
2

Here is a code sample and scaffold for you in which I use @VulgarBinary´s proposal.

private string sourcePath;
private string destinationPath;

public Form1()
{
    destinationPath = @"c:\users\name\desktop\"; // f.e.
    InitializeComponent();
}

//Browse Button
private void button1_Click(object sender, EventArgs e)
{
    using (OpenFileDialog dlg = new OpenFileDialog())
    {
        dlg.Title = "Open Image";
        dlg.Filter = "bmp files (*.bmp)|*.bmp"; // you can filter whatever format you want

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            sourcePath = dlg.FileName;
        }
    }

}

//Set Background Button
private void button2_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrWhiteSpace(sourcePath) && File.Exists(sourcePath))
    {
        destinationPath += Path.GetFileName(sourcePath);
        File.Move(sourcePath, destinationPath);
    }
}
monty.py
  • 2,511
  • 1
  • 17
  • 29
  • @VulgarBinary, thanks. Got it working but it moves the picture in the wrong folder. my target is C:\Windows\System32\oobe\info\backgrounds and it goes into C:\Windows\SysWOW64\oobe\info\backgrounds instead – Admiral Kitteh May 12 '15 at 00:25
  • 1
    Maybe this will help you: http://stackoverflow.com/questions/10100390/file-getting-copied-to-syswow64-instead-of-system32 – monty.py May 12 '15 at 17:16