How to know the number of Files opened by OpenFileDialog - c#

I can retrieve the names of individual files and also I can use count in the looping code to get the required value, but is it possible to know this without the iteration. Perhaps, a Property is defined for that.

openFileDialog1.FileNames.Length

Related

OpenFileDialog & SaveFileDialog Pop-up search with filter in C#

I have openFileDialog and saveFileDialog with filter (only .dvbcfg extention):
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "DVB Configuration File (*.dvbcfg)|*.dvbcfg";
saveFileDialog.DefaultExt = "dvbcfg";
saveFileDialog.AddExtension = true;
It works properly, but when I'm trying to type filename manually it shows files with any extentions w/o filtering and opens/saves them (first - open file, second - save file):
ScreenShot
How to show only files that matches saveFileDialog.Filter?
P.S. I have overwrite function in saveFileDialog.
UPD I have another option - throw an exception when user selected wrong filetype, but I have no idea how to get only file extention from saveFileDialog.FileName string.
At a certain point, you have to "trust" your users. You can steer them towards good ways of working with your program, but at a certain point, you have to recognise that you've put enough simple barriers in their way to prevent accidental misuse1 but you're unlikely to be able to create enough barriers (in these dialogs) to prevent malicious misuse.
The problem is that using wrong file may cause damage to expensive equipment (DVB-3030 Digital Modulator in this case) even if I'm using try/catch to get variables from files (they need to be integers, in try segment I have Convert.ToInteger32) and variable ranges in if/else checks (for example Frequency range should be 10MHz - 90 MHz with 100Hz step). Since program will be used by students, they can purposely try to break it.
And nothing in your current question (or sought answer) would prevent someone from renaming any arbitrary file to have a .dvbcfg extension.
At this point, you "trust" that the user has given you the filename they wish to use. What you need to do next is to validate the contents of the file. If it has a .dvbcfg extension but isn't actually a valid DVB config file, you need to reject it. If it doesn't have a .dvbcfg extension (hey, maybe they're working with an old file system that only allows 8.3 file names :-)) but turns out to have valid content, why be churlish and reject that file?
I would recommend more than just wrapping ToInteger32 calls in try/catch. Go through the file. Ensure it contains exactly what it should and nothing else. Read each parameter value and probably use TryParse on those. Because your code now "expects" to receive invalid inputs. Then validate ranges, etc.
1Which I'd say you've already got.

What would be the best way to save and retrieve an array of string in WPF

I need to save the last 10 paths (strings) of files found in a directory. What would be the best way to easily save and retrieve them?
I was thinking about reading and writing to a txt file but I was wondering if there was an easier more efficient way to do that in WPF.
You can use a Serializer to write the array to any kind of file: Json, xml, binary, anything. Then, when you need to load the array, you just Deserialize the file and you have your array variable again.
See this article on how serialization works for more information: https://learn.microsoft.com/en-us/dotnet/standard/serialization/
you can use settings to save your data.
do double click on settings and choose the type -> Browse -> system -> System.Collection.Specialized -> StringCollection .
and choose Scope as User.
just note that first time to use this collection you should create instance of it with new key word.
I know it is not easier. but i am sure it is cleaner.
to do this, first add this namespace:
using MyWpfApplication.Properties;
then use it in this way:
if (Settings.Default.MyStringCollection== null)
{
Settings.Default.MyStringCollection= new System.Collections.Specialized.StringCollection();
Settings.Default.MyStringCollection.Add("string1");
Settings.Default.MyStringCollection.Add("string2");
Settings.Default.Save();
}
else
{
var result = Settings.Default.MyStringCollection;
}
You can use a Configuration fileConfiguration file.
ConfigurationManager Class
I don't think it will support array. You would need path01 - path10.
If you want more of a List then use XML.

Quirky Directories

I've got an issue with some directory manipulation.
The problem is I have an archive of data that needs to be add or purge backup data based on a series of constraints. The constraint that is an issue is the archive only needs to keep the backup from the previous week.
So when you chart out the steps you would assume:
Check if directory exist.
Grab the files.
Then purge them.
Then move the following week into the directory.
The problem though is when you try keep the code simple and implementation, you create some code that doesn't feel like it is proper practice.
string[] archiveFiles = Directory.GetFiles(
Archive, #"*.*", SearchOption.TopDirectoryOnly);
foreach(string archive in archiveFiles)
File.Delete(archive);
So if you attempt to grab the files with Directory.GetFiles() and it doesn't return a value, according to the documentation:
Return Value Type: System.String[] An array of the full names
(including paths) for the files in the specified directory that match
the specified search pattern and option, or an empty array if no files
are found.
If it returns a null in the array then that would actually have the loop iterate once, an error. If it returns an array with no elements then it will ignore the loop. The second is what I believe it does, which makes this approach feel incorrect.
The only thing I could do would be to use File.Copy() as it can overwrite files, which would avoid this approach but even that could become suceiptable to the same dilemma of that empty array.
Is that right usage and approach for Directory.GetFiles() or is there a better way?
If it returns a null in the array then that would actually have the
loop iterate once, an error. If it returns an array with no elements
then it will ignore the loop. The second is what I believe it does,
which makes this approach feel incorrect.
If there are no files matching the list will be empty, there won't be nulls (how many nulls should return an empty directory?).
So your delete code will not be executed. Makes sense to me.
If you need to delete old files, then copy the new ones you may want to first move old files somewhere safe, then copy new ones, then to delete old files.
Maybe I didnt understand the problem here, but I don't see any. I hope actual code has some try catches though.

How to save variable values on program exit?

I am trying to use an ArrayList to store a variable number of strings, and would like to know how to save the ArrayList and its elements so that my windows form can recall their value between program load and exit.
I used to store the information in a text file, but would like to avoid external files if possible.
Thank you for any help you could provide.
You can save the ArrayList (if not ArrayList their are other equivalent classes) using Properties.Settings best part is it allows you the setting variable at Application and user level
A very good example can be found here how to use Settigns http://www.codeproject.com/Articles/17659/How-To-Use-the-Settings-Class-in-C
I've always done using (In Winforms in your case from the sounds of it), the Form_Closing to store to a Properties.Settings variable you'd create beforehand. If it's an ArrayList, you could store it to XML or a comma separated list. Your serizliation/deserialization method will depend on your data.
Have a look at isolated storage.
I used to store the information in a text file, but would like to avoid external files if possible.
Inevitably storing data between runs will require something outside the program's executables.
The registry would work, but the registry is not great for storing anything more than a small amount of information. A database could be used by that adds files.
For text strings a text file – one string per line1 – can be saved and loaded in a single statement. Putting the file into isolated storage or under a dedicated folder in %AppData% limits the chances of a user messing it up.2.
// Load
var theStrings = new ArrayList();
var path = GetSavePath();
if (File.Exists(path)) {
theStrings.AddRange(File.ReadLines(path);
}
// Save:
File.WriteAllLines(GetSavePath(), theStrings.ToArray());
Here using ToArray() as ArrayList doesn't implement IEnumerable<String> (List<String> would be a better choice for a collection and avoid this).
1 This assumes end of line is not valid inside the strings. If this needs to be supported there are a number of options. Some file format to separate the strings by another mechanism, or perhaps the easiest will be to escape characters with a simple transform (eg. \ → \\, newline → \n, and carriage return → \r).
2 You cannot prevent this without significant additional complexity that would use something like a service to load/save as a different user thus allowing the data to be protected by an ACL.

C#: a mechanism to generate regular files

following regular files (date_time.zip) would be generated at 15-min interval in ASP.NET site with Timer.
1027_0100.zip, 1027_011*.zip, 1027_0130.zip, ...
My question is I need a mechanism to restore files which are somehow missed within 3 days, like 1026_0000.zip. What data structure/algorithm would you recommend to use to implement?
PS: I intend to use another Timer to regularly restore missing files.
Thank you!
Since the naming scheme is know and the where the files are going is know. You simply need to generate what would be the name for each potential file and then check its existence using the System.Io.file.Exists. If that call fails regenerate the file.
I'll propose a slightly different solution: rather than querying the disk repeatedly, just use Directory.GetFiles(...) and Linq against that:
string[] files_that_should_exist = YourMethodToGenerateExistingFilenames();
string[] files_in_dir = System.IO.Directory.GetFiles(output_path);
var missing_files = files_that_should_exist.Except(files_in_dir);
foreach(string file in missing_files) YourMissingFileGenerateMethod(file);

Categories