OpenFileDialog does not allow '/' character even after disabling validation - c#

Similar question: How to avoid of file name validation in SaveFileDialog C#
I am writing an application that has an option to support opening executables and running them with given parameters, and I am trying to use OpenFileDialog as a user-friendly way to achieve this. After disabling AddExtension, ValidateNames, CheckFileExists and CheckPathExists, I can pass parameters to executables and the application runs them using the arguments as intended.
However, when I attempt to pass parameters that include "invalid" filename characters (such as '/'), I am stopped and get this example message:
and am not allowed to continue, even though ValidateNames is set to false.
Here is the code concerning the dialog:
OpenFileDialog dialog = new OpenFileDialog();
dialog.AddExtension = false;
dialog.CheckFileExists = false;
dialog.CheckPathExists = false;
dialog.ValidateNames = false;
if (dialog.ShowDialog() == DialogResult.OK) {
//Parse text manually here (parsing is fully handled on the developer side)
}
Is there any way to resolve this and completely disable input validation, or do I have to write a custom file dialog implementation?

You can't override the default validation. As such you will either have to ask for the parameters in a separate dialogue or re-implement the file open dialogue yourself.

Related

C# - Microsoft.Win32.SaveFileDialog Filename Issue

I have a problem where if you set the filename in the dialog box to a sub directory within the initial directory you set it to and then clicking 'Save', the dialog window doesn't actually save the file but opens the sub directory which I could still interact with.
For example If I set the initial directory for the dialog to 'C:\MainDir' and that directory consists of SubDir1, SubDir2, then in the save file dialog I could see that I am in the initial directory with two sub directories. If I set the filename to SubDir1 (no extension) in the dialog, and then I hit 'Save', what happens is instead of saving the file as 'filename.extension' the dialog opens the directory specified by the file name.
Here's what I currently have:
SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = ext;
dlg.AddExtension = true;
dlg.FileName = filename;
dlg.Filter = filter;
dlg.FileOk += OnFileDialogOk;
dlg.InitialDirectory = dir;
bool? dlgRes = dlg.ShowDialog();
Is this something that can be easily fixed?
Quick Answer: No.
You cannot override the default save method of Windows OS.
What you can do is perhaps to verify whether the filename you wanted to use (in this instance, SubDir) exists already as a directory. If it does, then you would need to change that name, as that will only manifest the behavior you've already seen.
Side Note: Just imagine you have a very important folder which contains critical files, and Windows would let you save a file that is named with that directory. That is a disaster waiting to happen.
The only ways I can think of doing this are a bit extreme:
You could roll your own dialog
You could modify the functionality of the standard dialog
The answers found here: Customizing OpenFileDialog could help with that.
I guess I should also note that while it may seem helpful to accommodate this kind of input and automatically append the extension, it'll be counter-intuitive to many users who will expect the default behaviour.
In short, I'd probably think twice about this.

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.

Always print to default printer even the printervname is specified

I created one windows application in which I need to print PDF files silently.
string printername="jn-01";
if (printername != "NULL")
{
using (PrintDialog pd = new PrintDialog())
{
pd.PrinterSettings.PrinterName = printername;
MessageBox.Show(printername);
pd.PrinterSettings.Copies = 1;
if (pd.PrinterSettings.IsValid)
{
ProcessStartInfo info = new ProcessStartInfo(e.FullPath);
info.Verb = "PrintTo";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(info);
}
}
I use above code for printing. But the system always print to default ptinter.
How can I solve this issue?
You are setting the printer name on a print dialog, but you aren't using the print dialog to print. Notice how you never use pd when printing. You are instead executing the PDF file (effectively using ShellExecute) with PrintTo verb. Now PrintTo verb supports providing the printer name as a command line argument. You can set it on info.Arguments. However for this to work, the default application that handles the PDF files needs to support it. See this page for more info on these verbs.
If the default PDF application has no support for this, then your alternative could be to call SetDefaultPrinter before printing and then restore it to its previous value after printing (Use GetDefaultPrinter to find which one is default first). Note that this changes the default printer for the user, so should not be the default choice when doing this.

Bug in C# OpenFileDialog if two fullstops in filename

I have an OpenFileDialog with the filter set to *.wav. However, when I execute the OpenFileDialog it also shows other files that includes .wav but the true extension is not .wav but e.g. png. Why is that and how can I avoid this?
Right now I take care of it when loading the file(s) for processing but I would like to avoid getting them in the OpenFileDialog list in the first place. Is this a bug in the control or is it me?
Background: I had by accident renamed a picture file to TheFile.wav.png - stupid, true, but these kind of things happens also for other users.
Thanks in advance
Try this to set the file type in the dialog:
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "wav files (*.wav)|*.wav";
dialog.InitialDirectory = #"C:\"; // You may not need this.
if (dialog.ShowDialog() == DialogResult.OK) // Or this; I was just being thorough.
{
// Your code can go here.
}
Just make sure that when using the .Filter property, you follow the pattern I have above, or else it won't work. Also, as was mentioned above, you may want to do some validation after the user selects something.

How can I get filename when user close Word?

I have one button and one textbox on form. When I click on the button, Microsoft Word is started. When the user closes Word, I want to get the file name that the user saved his work under to show up in the text box.
I am using the following code for button_click:
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(#"C:\Program Files\Microsoft Office\Office12\winword.exe");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process listFiles;
listFiles = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader myOutput = listFiles.StandardOutput;
listFiles.WaitForExit();
if (listFiles.HasExited)
{
System.IO.FileInfo ff = new System.IO.FileInfo(myOutput.ToString());
string output = myOutput.ReadToEnd();
this.processResults.Text = output;
}
I don't believe this is possible via the command line. Also, realize that, if the user opens another document, your code will not finish, since it'll wait until all of the docs are closed (the process won't end until that point).
That being said, you should be able to use the Word/Office Interop libraries, and listen to the DocumentBeforeSave and/or DocumentBeforeClose events. This should let you pull the information from the Document itself, right as it's being saved/closed.
I don't think you can do this with the current code you have. ProcessStartInfo is very generic and has no knowledge of word.
I think you will want to use Visual Studio Tools for Office (VSTO) to start word. This way you have a reference to the word application and document and can get the document name.
this article should get you started http://www.c-sharpcorner.com/UploadFile/mgold/WordFromDotNet11082005235506PM/WordFromDotNet.aspx the sample code has a object called aDoc. Then after the save you can check aDoc.FullName to get the path.
I'm not sure whether it's possible or not because name of the saved file is an internal information that's not public for other applications.
Instead in your particular case since you are using MS Word you can use Word interop to start the Word application in your application and then handle its events
Create a blank Word document in the desired location, and then get Word to load that?

Categories