Guillermo Prandi
Guillermo Prandi

Reputation: 1727

Detect when OpenFileDialog returns a downloaded URL/URI

I'm using OpenFileDialog (.Net Framework 4, Windows 10) and I've noticed that it will allow the user to specify a URL as the file name (e.g., http://somewebsite/picture.jpg). This is very useful for my application, so I don't intend to disable it. The way it works is downloading the file into the user's temp directory and returning the temporary file name in the dialog's Filename property. This is nice, except for the fact that the user starts to build up garbage in his/her temp directory.

I would like to tell when a file was downloaded by the OpenFileDialog class (as opposed to a previously existing file), so I can clean up by deleting the file after use. I could check if the file's directory is the temp directory, but that's not very good since the user might have downloaded the file him/herself.

I've tried intercepting the FileOK event and inspect the Filename property to see if it is an HTTP/FTP URI, but despite what the documentation says ("Occurs when the user selects a file name by either clicking the Open button of the OpenFileDialog") it is fired after the file is downloaded, so I don't get access to the URL: the Filename property already has the temporary file name.

EDIT: This is an example of what I'like to do:

Dim dlgOpenFile As New System.Windows.Forms.OpenFileDialog

If dlgOpenFile.ShowDialog(Me) <> Windows.Forms.DialogResult.OK Then Return

''//do some stuff with dlgOpenFile.Filename

If dlgOpenFile.WasAWebResource Then
    Dim finfo = New IO.FileInfo(dlgOpenFile.Filename)
    finfo.Delete()
End If

In this example, I've imagined a property to dlgOpenFile "WasAWebResource" that would tell me if the file was downloaded or originally local. If it's the first case, I'll delete it.

Upvotes: 4

Views: 954

Answers (1)

stuartjsmith
stuartjsmith

Reputation: 461

There's no obvious way to do this, but as a workaround, how about checking where the file lives? It looks like by default this dialog downloads files to the users Temporary Internet Files directory, so you could introduce some code that looks something like this:

FileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{

    string temporaryInternetFilesDir = Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache);
    if (!string.IsNullOrEmpty(temporaryInternetFilesDir) && 
                dialog.FileName.StartsWith(temporaryInternetFilesDir, StringComparison.InvariantCultureIgnoreCase))
    {
        // the file is in the Temporary Internet Files directory, very good chance it has been downloaded...
    }
}

Upvotes: 1

Related Questions