rem
rem

Reputation: 17045

WPF copy file to the predefined directory

In a WPF app I need to make it possible for a user to pick a file by the standard Open File Dialog and save it to the predefined folder (user doesn't know where it is) right after the user click OK button on Open File Dialog. Something like of importing a file to the application. I do it in the following way:

        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();            
        dlg.Filter = "Text documents (.txt)|*.txt"; 
        Nullable<bool> result = dlg.ShowDialog();
        if (result == true)
        {
            string filename = dlg.SafeFileName;
            System.IO.File.Copy(filename, @"E:\TestFolder\" + filename);
            MessageBox.Show("File " + filename + " saved");
        }

Is there a standard way to check if the file already exists before trying to save it and if it is really saved after saving it?

Upvotes: 1

Views: 5875

Answers (3)

Ian Durkan
Ian Durkan

Reputation: 1232

The System.IO.File.Exists method returns true if a file at the given path exists, so you could use it to check both before and after your copy operation.

Upvotes: 1

Daniel
Daniel

Reputation: 2832

Use the SaveFileDialog (Microsoft.Win32). If you try to save over a file that already exists it will prompt you to make sure you want to save over that file. This doesn'y actually save it though, all it will do is provide the name and location of the file you want to create/save over. After you use the SaveFileDialog to select the file you then need to do the work of saving the file.

This post may be helpful

Upvotes: 0

Mark Hall
Mark Hall

Reputation: 54532

Look at System.File.Exists that should be able to tell you what you need to know.

Upvotes: 4

Related Questions