Excluding file extensions from open file dialog in C# - c#

I am trying to put a filter on my C# openFileDialog that excludes certain file extensions. For example I want it to show all files in a directory that are not .txt files.
Is there a way to do this?

I don't think this is possible. The way the filter is set up, is that you can choose which files to show, but I don't think there's a way to show "All files except...". Come to think of it, have you ever seen an Open File Dialog in Windows that has this? I don't think I've ever seen one.
Your best bet is to let them choose all files, and then prompt the user if they select one that isn't allowed OR filter it down to all the possible files that you can deal with.

There is no direct way to do this using the BCL OpenFileDialog.
I can think of a couple of options:
1) Make a filter that just has all of the types you do want to support. This would be my recommendation, since that's the most common way of going about this type of operation.
2) Use something along the lines of this custom OpenFileDialog implementation. You could then override the OnFileNameChanged() method to potentially disable the "Open" button if the selected file has a .txt extension.
3) Let the user pick a .txt file, throw up an error dialog, and reopen the file dialog. This feels clunky and not too great to me, though....

Found with Google search "OpenFileDialog"
EDIT: Sorry about not expanding on the EXCLUDE aspects. You may not need to go to this extreme, but it would meet your needs....
Do a recursive directory search of all the files that the user may choose from. (Hopefully that's a small set of folders.)
Uniquely identify the extensions on those files. (System.IO.Path.GetExtension() and Linq's .Distint() method may work well here)
Remove the ".txt" entry from the list.
Construct a filter string by looping through these extensions.

I'm afraid this isn't possible. You'll either have to
a) Include a long list of all the extensions that should be allowed, or
b) Allow all extensions, and then use a simple check in code that reopens the dialog if the selected file has extension .txt.
Also, could you provide a bit more context for this question? I'm having trouble envisaging a scenario where I might explicitly need to exclude a certain extension. You can't probably get away with just a filter (and maybe a bit of checking in code) in almost all situations.

Here's a completely different approach, which you're unlikely to use.
Instead of using OpenFileDialog, analyze the specific features you need and create your own dialog box. You could easily provide whatever filtering you want, but then the difficulty moves over to the implementing and maintaining the new UI.
I don't suggest that you do this, but sometimes users are rather insistent upon what they need.
Another alternate: Instead of using a dialog, come up with something completely different that fits well within the app. This may not be possible, but then we don't know much about the app.

You cannot set a filter to exclude extensions from file dialogs.
You could however implement a delegate for the FileOk event on the dialog. This event fires just before the file the user selected will be accepted, and the event arguments provide a Cancel property that you can set to disallow selection.
It is not as elegant as actually making the wrong files invisible, but it will allow you to disallow selection of the wrong kind of file.
PS: Do not forget to give the user feedback why the file was not accepted, otherwise they may wonder why the dialog is not closing when they pick a 'txt' file.

Related

Dynamically add Image to ImageList that lasts in C#

I have this code to add an Image to ImageList :
imageList1.Images.Add(Image.FromFile(path));
I want to somehow save the image in my application(resources maybe?!) just like the way you add Image to ImageList at design time so if I move my application files somewhere else the added images move with it. I don't want to save files in application path or database or other things like that.
Is there any way to do that ?
Can you logically explain how that should work? Did you think this through?
just like the way you add Image to ImageList at design time
If you do this, they get COMPILED INTO THE PROGRAM AS RESOURCE. Which not only requires the compiler and the source code (though you can put them into a resource only assembly), but also access to changing the program files.
Doable at compile time, totally not a sane approach at runtime.
It also effectively stored them in a resource assembly in the application path, which you rule out as a location.
I don't want to save files in application path or database or other things
like that.
latest "other things like that" would ALSO rule out modifying the program (as it would store them somewhere) and make this a total fallacy request. You want to store images but not store them. Grats. Even if not:
Programs should NOT NEVER EVER modify themselves. This is a high priviledge operation, normal users can not change the program files folder.
As you rule out all other places - where you want to store the iamge? Cloud? Magic?
There is no way to do what you want because you rule out all possibilities. And "Like at design time" only seems to think you think this works by magic.
So, no - the question as you have asked it has one answer: get realistic. You can not rule out all ways to save them and then want them saved. Requirements contradict themselves.

Setting OpenFileDialog Restrictions

I have a Windows Form application and I use a custom control that allows users to select and save image. However I need to insert some restrictions. The easy one was to select only jpg files but now I need to restrict the users to be able to see and select only jpg images with certain pattern in the name and if possible (I think I've seen this implemented in other windows applications) I want this pattern to stay in the File Name field and the user to not be able to delete it.
what I have done till now :
I have the restriction set:
fileNameFilter = "All files (*.jpg)|" + ImageNameFilter + "*.jpg";
openFileDialog1.Filter = fileNameFilter;
I can show the user what pattern he needs to look for:
openFileDialog1.FileName = fileNameFilter;
However there are two things that I still can't accomplish. Here is a print screen to make it clear:
First - the pattern is shown but I can delete it when it's made like this and I want if it's possible the File name field to be Read only or in other words the user should not be able to delete what I have put there.
Second - this is the list with previously opened files even though the file don't match the name restrictions/filters the user is still able to select form the list and save that file. I need, again if possible either to clean this list when the File Dialog is opened or somehow to stop the user from being able to save this file but i think the second will require too much extra business logic so I prefer just to clean the list.
Trying to control rigidly what's shown in a file dialog through a filter or a file name pattern is not going to work. The user can always type their own pattern into the file name edit box.
What you need to do is use the file dialog's facilities for controlling what objects are displayed. Unfortunately the C# wrapper doesn't expose this functionality that is offered by the underlying Win32 controls.
If you need to support XP, then you need to listen for the CDN_INCLUDEITEM notification. This is sent for each item in the folder. You therefore get the opportunity to either allow or deny the inclusion of each item.
For the dialogs used in Vista and later it's different. These dialogs use IFileDialog. You need to call the SetFilter method to add a filter. That filter is your implementation of IShellItemFilter which again controls inclusion using the IncludeItem method.
It's going to be a bit messy to make all this happen from C#, but this is the correct way to do what you ask. Once you do this, there's no need to even think about trying to make the file name edit box read-only. Because the dialog will only offer up the items that you have allowed to be included.
No.
Two solutions: check the filename after Open-click (which you should do anyway), or create your own control that displays files that do match your filename pattern.

How to track directory opening

I'm not sure if the question's title makes sense, and I'm sorry if it doesn't; I didn't really know what to title it.. Anyway, is there a way to make your program track the viewing of a folder?
What I'm trying to achieve: Windows 7 Home Premium doesn't allow encryption. So, I made a folder inside my user directory, and set it to hidden. Although, you can easily find it by changing windows settings.. So, is there a way to make a program pull up a window if the user tries to access that certain folder?
I don't think you can detect the "opening" of a folder.
Instead, you may want to set a FileSystemWatcher to detect any file access to the files in that particular folder.
Hope this helps.
First of all, I have to wonder why you're not just setting an ACL on the directory to prevent access.
However, it sounds like you want to find when somebody is accessing a particular directory. To do this, you enable filesystem auditing, then set the audit ACL to generate audit entries for "List folder". This will cause entries to be generated in the Security Event Log whenever the directory is viewed.
Now you just have to write a program that watches the Security event log looking for entries indicating that somebody has listed the directory in question and take action as necessary.
Well, there is an article on code project describing how you can hook into windows system calls: http://www.codeproject.com/KB/system/hooksys.aspx - it's not simple though (and also not C#) and has the potential to screw with your system but if it might be a fun project to work on.
A simpler option would be: Use a 3rd party desktop encryption tool - not much programming involved here but it might do the job better than anything else.

Regular expression to filter files in OpenFileDialog

I would like to know how to filter files in a open file dialog (in winforms)
based on a regular expression. Files have all same extensions (.xml).
Big files are split up into several files with the same name only to be separated with _1 ...
We only want to show the files without _1 (first data file)
the open file dialog has a property filter but i dont know how to specify this in our filename format, hence the regular expression.
Thankx,
Niki
I don't think you can do it with the OpenFileDialog's Filter property, which just filters list of files based on extension.
I think you'll have to let the user choose an xml file, validate and then pop up the dialog again if its a _1 file. You can subscribe to the FileOK event and slot in this validation in there. You can use regular expressions to validate the filename here. That's the best that can be done.. I guess.
The OpenFileDialogEx described in this CodeProject article is an extension of the standard OpenFileDialog. The primary intention of that extension is to modify the display of the dialog, but there are some additional bells and whistles. For example, OFDEx adds a few events, for File changed, Folder change, etc.
Someone pointed out that the CDN_INCLUDEITEM notification seems like it would satisfy the desire to filter the list of files shown in the dialog,. It seems like it would, but it does not. The CDN_INCLUDEITEM does not do what you might think or want.
According to this MSDN Mag article,
If you create your dialog with
OFN_ENABLEINCLUDENOTIFY, Windows sends
your hook procedure a CDN_INCLUDEITEM
notification for every item it adds to
the open list. If you return FALSE,
Windows excludes the item. The problem
is, Windows doesn't notify you for
ordinary files, only pseudo-objects
like namespace extensions. When you
read the documentation through a
magnifying glass, the print is
perfectly clear: "The dialog box
always includes items that have both
the SFGAO_FILESYSTEM and
SFGAO_FILESYSANCESTOR attributes,
regardless of the value returned by
CDN_INCLUDEITEM." Apparently the
Redmondtonians added CDN_INCLUDEITEM
for their own purposes, which didn't
include filtering ordinary file names.
In other words, in response to CDN_INCLUDEITEM, you cannot return FALSE for regular files, to exclude them from the dialog. In contrast to the doc which says, the response from the CDN_INCLUDEITEM is ignored for regular files, in my experience, the CDN_INCLUDEITEM is not even sent for regular files, at least not on my Vista machine.
So is it possible to exclude files dynamically? Well, yes, in C++; In response to the CDN_FOLDERCHANGED message, you can get and set the contents of the CListCtrl that contains the files. I haven't figured out how to set this list in C#.
The OpenFileDialog does not support this. An alternative is to use a 3rd party control like FileView which lets you filter items using any criteria you wish such as regular expressions.
You should be able to do it with the following filter:
Data Files|*_1.xml
I'm not sure how to do it in C# with WinForms, but in C++, what you would do is install a custom hook procedure and listen for the CDN_INCLUDEITEM notification. Then, you check each filename against your regex. See http://msdn.microsoft.com/en-us/library/ms646960(VS.85).aspx#_win32_Filters.

Hooking my program with windows explorer's rename event

Is there any way, in any language, to hook my program when a user renames a file?
For example:
A user renames a file and presses enter (or clicks away) to confirm the rename action. BEFORE the file is actually renamed, my program "listens" to this event and pops up a message saying "Are you sure you want to rename C:\test\file.txt to C:\test\test.txt?".
I'm thinking/hoping this is possible with C++, C# or .NET.. But I don't have any clue where to look for.
You can probably solve this by using the FileSystemWatcher class in .NET framework.
From the class remarks:
You can watch for renaming, deletion,
or creation of files or directories.
For example, to watch for renaming of
text files, set the Filter property to
"*.txt" and call the WaitForChanged
method with a Renamed specified for
its parameter.
My guess is that this is not possible, I did find this which is for monitoring operations (including rename) on a folder, but there does not appear to be a similar method for files.
#Richard, FileSystemWatcher is good if you only need to monitor changes, but he needs to interrupt them which it cannot do.
IFileOperationProgressSink.PreRenameItem is the closest supported thing I know of. Unfortunately, it's not a hook into Explorer - so you can only use it for your own IFileOperation actions. Depending on your needs, you can write a shell extension to do your own ConfirmRename (or something), and branch from there.
Otherwise, you're looking at hooking SHFileOperation, I think. This would have to be done in unmanaged code, as you'll be loaded into Explorer.exe. For Vista, this has been changed to IFileOperation - which probably means you'll have to hook the creation of it and pass out your mock.
Personally, I think since you're talking a rename, wilhelmtell's idea of confirming after the change, and undoing it if necessary is the best idea.

Categories