C#- How to use OpenFileDialog to load a ConfigurationUserLevel file? - c#

I want to be able to load a config file (.config) of type System.Configuration.ConfigurationUserLevel using OpenFileDialog.
I need the file to be a ConfigurationUserLevel because the I need to use .AppSettings, as its functionality already exists in many other places throughout my code.
Currently I have,
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var extension = Path.GetExtension(openFileDialog1.FileName);
if(extension.Equals(".config"))
{
try
{
var configFile = (ConfigurationUserLevel)openFileDialog1.OpenFile();
var settings = configFile.AppSettings.Settings;
but I get an error saying that I cannot simply convert from a Stream to ConfigurationUserLevel.
Is there a way for me to get a ConfigurationUserLevel file from an openFileDialog? Or is there a workaround?

OpenFileDialog just helps users to get FileName, of course you can't open file directly with openFiledialog.OpenFile().
You need to read file with FileName from OpenFileDialog, and parse it then cast to ConfigurationUserLevel.
This can be help: https://msdn.microsoft.com/en-us/library/system.io.file(v=vs.110).aspx

Related

C# WPF Have User select file then use the functions within that file

I'm new to using C# and WPF so I apologize if my terminology is incorrect.
I want trying to make a program to automate small businesses workflows, the base application is the same for everyone, but how their order data is structured is going to be different.
So, my goal would be to build them a custom file that contains function on how to parse their order data, then have the user drag and drop that file into the application to which the application would use it.
I have a way for them to select the file and move it into the applications directory here:
private void SelectFile_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".cs";
dlg.Filter = "C# Files (*.cs)|*.cs";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filePath = dlg.FileName;
string relPath = AppDomain.CurrentDomain.BaseDirectory;
string destPath = System.IO.Path.Combine(relPath, dlg.SafeFileName);
Trace.WriteLine(destPath);
File.Move(filePath, destPath, true);
}
}
But now I run into an issue when I want to call from that file I get a error "CS0103" the file doesn't exist in the current context. So I am now unable to run the application
Is there a way around this error? so it will only run when the file exists and get rid of this error?
I have tried to check if the file exists before calling it, but the same error prevents me from running my app.
//call your order parser script
if (File.Exists("OrderParser.cs"))
{
OrderParser.OrderParser.Parser(item);
}

Export text to a browsed file in wpf

I'm trying to export some text to a file browsed by the user and create it if this file does not exists.
What I've done till now is to use OpenFileDialog but I don't know if it's the right way to do it and also if it is I don't know how to continue
You can use the SaveFileDialog()
var dialog = new SaveFileDialog();
dialog.ShowDialog();
var path = dialog.FileName;
File.WriteAllText(path, "YourData");

C# WPF - Only allow certain file extensions

I have an OpenFileDialog and I only want to allow .txt as a valid file for the users.
I know I can add a Filter to the OpenFileDialog like so:
var dialog = new OpenFileDialog();
dialog.DefaultExt = ".txt";
dialog.Filter = "Text Files (*.txt)|*.txt";
var result = dialog.ShowDialog();
// Do something with the result
The problem however, is that I can still directly say something like "test.jpg" in the OpenFileDialog and then it opens this uploads this .jpg file. (Obviously it goes wrong somewhere later, but that doesn't matter for now.) I just want to know how I can restrict the user to only add ".txt" files, nothing else? (By directly validation it inside the OpenFileDialog, instead of doing it somewhere later.)
You cant do that only in OpenFileDialog and even if you could its a bad limitation.
Using the *.txt example there are multiple files extensions that are plain text inside, *.bat or all the codding file extensions *.cs, *.js, etc...
You should not limit the user on what file he can put on it.
For more complex file types if your program cant handle the file passed by the user you should show an error not prevent the user from passing the file.

OpenFileDialog xml Filter allowing .htm shortcuts

I've filedialog in winforms.
It is set to read only .xml files.
ofd.DefaultExt="xml";
ofd.Filter="XML Files|*.xml";
but when I run it is allowing to upload .htm file shortcut. whereas it should not show .htm file at all.
You're doing it correctly. Using the Filter property allows you to limit the files displayed in the open dialog to only the specified type(s). In this case, the only files the user will see in the dialog are those with the .xml extension.
But, if they know what they're doing, it's trivial for the user to bypass the filter and select other types of files. For example, they can just type in the complete name (and path, if necessary), or they can type in a new filter (e.g. *.*) and force the dialog to show them all such files.
Therefore, you still need logic to check and make sure that the selected file meets your requirements. Use the System.IO.Path.GetExtension method to get the extension from the selected file path, and do an ordinal case-insensitive comparison to the expected path.
Example:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML Files (*.xml)|*.xml";
ofd.FilterIndex = 0;
ofd.DefaultExt = "xml";
if (ofd.ShowDialog() == DialogResult.OK)
{
if (!String.Equals(Path.GetExtension(ofd.FileName),
".xml",
StringComparison.OrdinalIgnoreCase))
{
// Invalid file type selected; display an error.
MessageBox.Show("The type of the selected file is not supported by this application. You must select an XML file.",
"Invalid File Type",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
// Optionally, force the user to select another file.
// ...
}
else
{
// The selected file is good; do something with it.
// ...
}
}

How to save the file in a path chosen by the user

I am importing a source file and processing it and then after that I have to save it in a new location. I have created the syntax for importing file, tell me the syntax to save it to a new location. One is when I am calling the constructor to give the path of import file, then I can also give the path for the output location. But don't know how to implement it. Please tell.
You can use a SaveFileDialog pretty much like this:
using ( var dlg = new SaveFileDialog() )
{
if ( dlg.ShowDialog() == DialogResult.OK )
{
//SAVE THE OUTPUT
//DEPENDING ON THE FORMAT, YOU MAY WANT TO USE
//File.WriteAllBytes(dlg.FileName, yourBytes);
//File.WriteAllText(dlg.FileName, yourText);
//File.WriteAllLines(dlg.FileName, yourStringArr);
//OR ANY OTHER CODE YOU WANT TO USE TO PERSIST YOUR DATA
}
//else the user clicked Cancel
}
Also, you can set a default extension, a default path and more. Look up SaveFileDialog's information on MSDN
As your importing the file you could use the StreamWriter base class to write it to a file that the end user designates in a either a text box or a file upload box.

Categories