简体   繁体   中英

How do I use FileDialog to create a directory, then automatically copy files to new directory?

In my program, I would like to use a FileDialog to access audio files, then automatically copy the selected file(s) to a new folder upon clicking "open". I want to do this so I can make changes to a sample without changing the original file.

My problem is that whenever I select a file then click "open" in the file dialog, the program crashes or closes.

        OpenFileDialog open = new OpenFileDialog();
        open.Filter = "Wave File (*.wav)|*.wav;";
        if (open.ShowDialog() == true)
        {
            bool directoryExists = Directory.Exists(@"C:\Documents\LUX\Soundbites\");
            if (directoryExists == true)
            {
                string[] files = open.FileNames;

                foreach (string file in files)
                {
                                            
                    var info = new FileInfo(file);                          

                    File.Copy(file, @"C:\Documents\LUX\Soundbites\", true);
                }
            }

            if (directoryExists != true)
            {
                Directory.CreateDirectory(@"C:\Documents\LUX\");
                Directory.CreateDirectory(@"C:\Documents\LUX\Soundbites\");
                string[] files = open.FileNames;

                foreach (string file in files)
                {
                                            
                    var info = new FileInfo(file);    

                    File.Copy(file, @"C:\Documents\LUX\Soundbites\", true);
                }
            }
        }

I'm sure this is a common operation, but I'm new to developing and I haven't found any real answers online.

File.Copy的第二个参数需要您在File.Copy代码中将文件复制到的文件名,而不是目录,将其更改为:

File.Copy(file, @"C:\Documents\LUX\Soundbites\" + System.IO.Path.GetFileName(file), true);

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