简体   繁体   中英

How can I move a user chosen file to a user chosen directory in Visual C#?

I'm trying to make a program that can move any file the user selects into a different folder. I've looked around and gathered some information and put something together but it doesn't quiet work, but it doesn't have give any errors either. Could someone tell me whats wrong with it and or how to fix it? (This is my first test with Visual Studio + C# keep in mind)

Here is the code (inside a button):

if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string sourceFile = openFileDialog1.InitialDirectory + openFileDialog1.FileName;

            var dirPath = @"C:\Users\goverpie\Desktop\Server\Plugins\";
            var extn = Path.GetExtension(sourceFile);

            var finalName = sourceFile + extn;
            var targetFilePath = Path.Combine(dirPath, sourceFile);

            File.Move(sourceFile, targetFilePath);

        }

So, the project builds and runs fine, and it opens up the dialog box, but when I choose a file, the dialog box closes as normal and nothing was moved.

Thank you!

Your sourceFile string contains .InitialDirectory as well as .FileName , so (if I read this correctly), selecting C:\\TEMP\\myFile.foo as your target file, the targetFilePath would end up being C:\\Users\\goverpie\\Desktop\\Server\\Plugins\\C:\\TEMP\\myFile.foo . Given that the system will throw an error when it finds a : in the path, you're probably not handling the exception that gets thrown and the system is just quitting.

Put a break point at the File.Move(sourceFile, targetFilePath); line and see what the values are. Also, wrap the whole thing in a try/catch block and trap exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM