c# - How to disable path exist check in OpenFileDialog? - c#

follwing simple code:
Microsoft.Win32.OpenFileDialog _fileDialog = new Microsoft.Win32.OpenFileDialog();
_fileDialog.Title = CarPlus.Base.Properties.Resources.ContentSettingsDatabase_FileOpen_TitleRestore;
_fileDialog.CheckPathExists = false;
_fileDialog.CheckFileExists = false;
_fileDialog.ValidateNames = false;
_fileDialog.Multiselect = false;
_fileDialog.InitialDirectory = _searchPath == null ? System.Environment.SpecialFolder.MyComputer.ToString() : _searchPath;
_fileDialog.Filter = "Wiederherstellungsarchiv (*.fbk)|*.fbk";
// Display OpenFileDialog
if (_fileDialog.ShowDialog() == true)
return (_fileDialog.FileName);
return (null);
the sense is to give the user the possibility to select a file or to write down his own path and file name. that is necessary, because the selected file is a database backup file for a firebird instance. the firebird server will use this file to restore the database but he mus have access to that file and of course, if the firebird instance is running on another computer the file path can be different.
my problem is, if i write down in the dialog 'c:\bar.fbk' is everything fine even when the file not exist on the local computer, but if i write 'c:\foo\bar.fbk' i will get an error message that the path not exist.
but why? my filedialog setup includes
_fileDialog.CheckPathExists = false;
who knows why?

Related

Inhibit Input Validation on CommonOpenFileDialog in Win API Pack

This is a WPF app with the latest version of the .NET framework and VS2015
on a Win 10 box.
I am trying to use the "CommonOpenFileDialog" from the Windows API code pack 1.1
to allow the user to establish a folder in which to do some stuff. The folder
can be either an existing folder, or a new one that the user specifies.
If the user wants to create a new folder, then I want them to be able to specify
the folder by editing the text within the "Folder:" textbox at the bottom of the
dialog. Within this context, the dialog would just be a means by which to
navigate to the folder in which the new one is to be created. My plan is to
validate the input within my code to check for a valid (existing) path, and
simply create the path if it does not exist.
Here is the code:
private void test1_folderSelectorDialog ()
{
if (CommonFileDialog.IsPlatformSupported)
{
var folderSelectorDialog = new CommonOpenFileDialog();
folderSelectorDialog.EnsureReadOnly = false;
folderSelectorDialog.IsFolderPicker = true;
folderSelectorDialog.Multiselect = false;
folderSelectorDialog.EnsureValidNames = false;
folderSelectorDialog.EnsurePathExists = false;
folderSelectorDialog.EnsureFileExists = false;
folderSelectorDialog.InitialDirectory
= "C:\\My_Initial_Directory";
folderSelectorDialog.Title = "test1_folderSelectorDialog";
if (folderSelectorDialog.ShowDialog() == CommonFileDialogResult.Ok)
TxBx_folder.Text = folderSelectorDialog.FileName;
this.Focus();
}
else
MessageBox.Show ("CommonFileDialog is not supported");
}
When I run the dialog and modify the text within the "Folder:" textbox,
then press "Select Folder", the dialog validates the input and issues a
dialog popup with the message:
"Path does not exist. Check the path and try again."
Please note that I have set "EnsureValidNames", "EnsurePathExists", and
"EnsureFileExists" to "false". (If they do not control dialog validation,
then what are they there for?)
I can right-click on the dialog window and use "new > Folder" to create a
new folder (which is what I'll have to do if I cannot resolve this issue),
but I'd rather do it the way that I am trying to do it, as it seems much
easier and more intuitive to do it that way.
How do I get the silly thing to shaddup and just accept the input without
passing judgement upon it?
Thanks!
If you want the user to select only the folder, then below code is enough
CommonOpenFileDialog dialog = new CommonOpenFileDialog()
dialog.IsFolderPicker = true
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
filesPath = dialog.FileName
}
I believe below things are not required
folderSelectorDialog.Multiselect = false
folderSelectorDialog.EnsureValidNames = false
folderSelectorDialog.EnsurePathExists = false
folderSelectorDialog.EnsureFileExists = false

C# Why does System.IO.File.Exists keep coming up false?

string profile = "\\" + txtProfileLoad.Text + ".txt";
profile = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + profile;
The variable profile is receiving the correct file path, but when I run it the File.Exists comes up false every time.
if (System.IO.File.Exists(profile) == true)
{
System.IO.StreamReader profileReader;
profileReader = new System.IO.StreamReader(profile);
do
{
profileLevel = profileLevel + profileReader.ReadLine() + "\r\n";
} while (profileReader.Peek() != -1);
loadName(profileLevel);
wordBeingUsed.finalWord = loadedName;
Close();
}
else
{
MessageBox.Show("Invalid file name. Please try again.");
}
There aren't any permissions stopping it from seeing the file.
Any help with this would be appreciated. It's been driving me crazy.
Is this a pre-existing file that you are trying to read? Or is this a new file that you are hoping to create? What is the value inside txtProfileLoad.Text, issue most likely is within this property.
Run a sanity check:
var profile = "mytestfile.txt";
var myFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), profile);
File.WriteAllText(myFile, "Testing file write");
if (File.Exists(myFile))
{
// Access works.
}
else
{
//Didn't work
}
If above code works, then it is most likely that the name you create from txtProfileLoad.Text is different from actual file on the drive. On the other hand, if this is a file that doesn't exist yet; then of course it would return false when you check Exists.
You can use a string variable and pass the file name to it:
string tempFile = txtProfileLoad.Text;
string profile = #"C:\temp\tempfile.txt";
Also check out if you could use the file open method instead of File.Exist.
As per MSDN:
true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. This method also
returns false if path is Nothing, an invalid path, or a zero-length
string. If the caller does not have sufficient permissions to read the
specified file, no exception is thrown and the method returns false
regardless of the existence of path.
Have you tried running as an administrator? Try do "right click" on the Visual Studio icon and select "Run as Administrator", and see if you still encounter the same behaviour.

microsoft.win32.savefiledialog issue in windows xp

I am using microsoft.win32.savefiledialog to save a file inside a folder. Only in windows XP, after saving file in a folder (ex: abc) , I cannot delete abc folder. Error message displays saying that another process is using this. Seems like handles are remaining on selected folder. Please give me a solution on this.
Following is my save file dialog code:
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.DefaultExt = !string.IsNullOrEmpty(this.DefaultExtension) ? this.DefaultExtension : "*.*";
fileDialog.Filter = !string.IsNullOrEmpty(Filter) ? Filter : "All Files|*.*";
fileDialog.FileName = !string.IsNullOrEmpty(this.FileName) ? this.FileName : string.Empty;
fileDialog.InitialDirectory = !string.IsNullOrEmpty(this.DefaultPath) ? this.DefaultPath : string.Empty;
if (fileDialog.ShowDialog().Value == true)
{
fileName = fileDialog.FileName;
}
else
{
fileName = string.Empty;
}
return fileName;
EDITED :
This is common for System.Windows.Forms also, I tried lot, issue happnes when I select a folder from file dialog window. no need to do anything after that, just select a folder form save file dialog. that foldercannot be deleted .
This is entirely normal. It is not another process that has the directory object opened, it is your process. Your code made the directory the default working directory of your process. Something you can see from the Environment.CurrentDirectory property.
Set the SaveFileDialog.RestoreDirectory property to true to avoid this.

How can I get the CommonOpenFileDialog's InitialDirectory to be the user's MyDocuments path, instead of Libraries\Documents?

I'm using the CommonOpenFileDialog in the Windows API Code Pack as a folder picker dialog. I'm setting the InitialDirectory property to Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments). However, when I display the dialog, the path in the address bar is Libraries\Documents (not C:\users\craig\my documents as I'd expect). Additionally, if I just press the Select Folder button, I get a dialog saying that 'You've selected a library. Please choose a folder instead.'
Does someone know why my file path is being ignored, in favor of 'libraries\documents'? More importantly, how can I get the dialog to respect the InitialDirectory value I passed in?
The code I'm using for the dialog is:
if (CommonFileDialog.IsPlatformSupported)
{
var folderSelectorDialog = new CommonOpenFileDialog();
folderSelectorDialog.EnsureReadOnly = true;
folderSelectorDialog.IsFolderPicker = true;
folderSelectorDialog.AllowNonFileSystemItems = false;
folderSelectorDialog.Multiselect = false;
folderSelectorDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
folderSelectorDialog.Title = "Project Location";
if (folderSelectorDialog.ShowDialog() == CommonFileDialogResult.Ok)
{
ShellContainer shellContainer = null;
try
{
// Try to get a valid selected item
shellContainer = folderSelectorDialog.FileAsShellObject as ShellContainer;
}
catch
{
MessageBox.Show("Could not create a ShellObject from the selected item");
}
FilePath = shellContainer != null ? shellContainer.ParsingName : string.Empty;
}
}
Thanks,
-Craig
First of all, I'm sorry it took me so long to understand your question.
The message I see is when I try this is:
Cannot operate on
'Libraries\Documents' because it is
not part of the file system.
There's not much more to say. A library is a virtual folder that is an amalgamation of various different real folders.
There's no real way to avoid this error. You have asked the dialog to return a folder and the user has not selected a folder. The dialog therefore cannot fulfil its part of the deal.
If you descend further into the folder structure, into real folders, then the dialog will return you a real value.
Instead of
folderSelectorDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
try
folderSelectorDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

IManExt ImportCmd trouble

I have been writing a small application using C# to copy a document into an individuals 'My Documents' folder on our DMS server.
I've beased the code around the listing provided in the 'WorkSite SDK 8: Utilize the IMANEXT2Lib.IManRefileCmd to File New Document Folders' blog.
Using this code in a WinForm application I have no problems copying the file from the source folder into the users DMS 'My Documents' folder.
However if I use the code in a command line application/.dll or any other type of application (other than WinForm) during the copy process I receive the error messages;
1.
Error occurred when try to log the event!
IManExt: Error occurred when try to log the event!
Access is denied.
2.
The document was imported to the database, but could not be added to
the folder.
IManExt: The document was imported to the database, but could not be
added to the folder.
IManExt.LogRuleEventsCmd.1: Error occurred when try to log the event!
IManExt.LogRuleEventsCmd.1: Access is denied.
Error occurred when try to log the event!
-%-
Does anyone know why I'd receiving the 'Access Denied' error messages when using a non-WinForms application to copy documents?
What would I need to do to get around this issue?
Any help would be amazing!
Code in place:
public void moveToDMS(String servName, String dBName, String foldName)
{
const string SERVERNAME = servName; //Server name
const string DATABASENAME = dBName; //Database name
const string FOLDERNAME = foldName; //Matter alias of workspace
IManDMS dms = new ManDMSClass();
IManSession sess = dms.Sessions.Add(SERVERNAME);
sess.TrustedLogin();
//Get destination database.
IManDatabase db = sess.Databases.ItemByName(DATABASENAME);
//Get destination folder by folder and owner name.
IManFolderSearchParameters fparms = dms.CreateFolderSearchParameters();
fparms.Add(imFolderAttributeID.imFolderOwner, sess.UserID);
fparms.Add(imFolderAttributeID.imFolderName, FOLDERNAME);
//Build a database list in which to search.
ManStrings dblist = new ManStringsClass();
dblist.Add(db.Name);
IManFolders results = sess.WorkArea.SearchFolders(dblist, fparms);
if (results.Empty == true)
{
//No results returned based on the search criteria.
Console.WriteLine("NO RESULTS FOUND!");
}
IManDocumentFolder fldr = null;
if (results.Empty == false)
{
//Assuming there is only one workspace returned from the results.
fldr = (IManDocumentFolder)results.ItemByIndex(1);
}
if (fldr != null)
{
// Import file path
string docPath = #"C:\Temp\";
string docName = "MyWord.doc";
// Create an instance of the ContextItems Collection Object.
ContextItems context = new ContextItemsClass();
// Invoke ImportCmd to import a new document to WorkSite database.
ImportCmd impCmd = new ImportCmdClass();
// The WorkSite object you pass in can be a database, session, or folder.
// Depends on in where you want the imported doc to be stored.
context.Add("IManDestinationObject", fldr); //The destination folder.
// Filename set here is used for easy example, a string variable is normally used here
context.Add("IManExt.Import.FileName", docPath + docName);
// Document Author
context.Add("IManExt.Import.DocAuthor", sess.UserID); //Example of a application type.
// Document Class
context.Add("IManExt.Import.DocClass", "BLANK"); //Example of a document class.
//context.Add("IManExt.Import.DocClass", "DOC"); //Example of a document class.
// Document Description (optional)
context.Add("IManExt.Import.DocDescription", docName); //Using file path as example of a description.
// Skip UI
context.Add("IManExt.NewProfile.ProfileNoUI", true);
impCmd.Initialize(context);
impCmd.Update();
if (impCmd.Status == (int)CommandStatus.nrActiveCommand)
{
impCmd.Execute();
bool brefresh = (bool)context.Item("IManExt.Refresh");
if (brefresh == true)
{
//Succeeded in importing a document to WorkSite
IManDocument doc = (IManDocument)context.Item("ImportedDocument");
//Succeeded in filing the new folder under the folder.
Console.WriteLine("New document number, " + doc.Number + ", is successfully filed to " + fldr.Name + " folder.");
}
}
}
}
Just in case this helps someone else.
It seems my issue was the result of a threading issue.
I noticed the C# winform apps I had created were automatically set to run on a single 'ApartmentState' thread ([STAThread]).
Whereas the console applications & class library thread state and management hadn't been defined within the project and was being handled with the default .NET config.
To get this to work: In the console application, I just added the [STAThread] tag on the line above my Main method call.
In the class library, I defined a thread for the function referencing the IMANxxx.dll and set ApartmentState e.g.
Thread t = new Thread(new ThreadStart(PerformSearchAndMove));
t.SetApartmentState(ApartmentState.STA);
t.Start();
In both cases ensuring single 'ApartmentState' thread was implemented set would resolve the issue.

Categories