C# WPF FolderBrowserDialog - Unable to retrieve the root folder - c#

I am using the FolderBrowserDialog to select the Folder where user can save file. While opening the folder browse dialog, application get crashed and raised below exception.
System.InvalidOperationException: Unable to retrieve the root folder.
at System.Windows.Forms.FolderBrowserDialog.RunDialog(IntPtr hWndOwner)
at System.Windows.Forms.CommonDialog.ShowDialog(IWin32Window owner)
at TestApp.GenerateExcelReport()
Users are using the applications from cloud as My application is launched on Citrix Environment. Hence not all the users has facing this issue but few of them are facing.
string folderPath = "X:\\Reports";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.ShowNewFolderButton = true;
folderDialog.SelectedPath = folderPath;
DialogResult dialogResult = folderDialog.ShowDialog();
if (dialogResult == DialogResult.OK)
{
folderPath = folderDialog.SelectedPath;
}
else
{
return;
}
Kindly suggest what can be the root cause of getting this issue while showing the FolderBrowseDialog. Also, suggest the potential fixes to prevent this exception.
Thanks & Regards,
Hiren Lad

This occurs for me when the folder %USERPROFILE%\Desktop doesn't exist. Creating that folder resolved the issue. Note that File Explorer may show a Desktop folder in %USERPROFILE% even if Desktop doesn't actually exist. You can verify whether Desktop exists by running dir %USERPROFILE% in cmd.

I'm late but the fix for this issue might be if you set the RootFolder property of FolderBrowserDialog other than the default RootFolder.
e.g
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.RootFolder = Environment.SpecialFolder.MyComputer;

Related

C# Folder browse Dialog not showing Network shared folders win10

I have created an application(windows) compiled with .NET 4.6.1 and used the FolderBrowserDialog object. When a button is pressed I execute this code:
FolderBrowserDialog folderbrowserdialog = new FolderBrowserDialog();
folderbrowserdialog.Description = "Custom Description";
if (folderbrowserdialog.ShowDialog() == DialogResult.OK)
{
filePath = folderbrowserdialog.SelectedPath ;
}
what i get from the folderbrowserdialog(like foto)
however ,the folder browserdialog is not showing the networks shared folder(that the purpose of my app) otherewise just the pc folders.
but what i want to get it is the network shared folders which could i also access from windows 10 like foto here:
notes to be marked:
i could not use the open file dialog cause i need the folder location.
i desgined the Appto be opened just like admin by adding manisfest so the app is always starting like admin.
the app should be comptiable with windows 10,7
note i know that i could try setting this registry option (could be broken in Win10):
HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Policies/System
EnableLinkedConnections=1
but it does not make a sense to add this registry by every customer PC
so is there any tipps to show the network shared folders in FolderBrowserDialog ?
Finally after reading many topics i found that the only solution is to add a Registry key programmatically so here how to add specfic C# Registry Subkey with dword value:
i wrote a method wich could all use it
just to let you know after using it you have to restart the device after it ,it will work ;)
public void ConfigureWindowsRegistry()
{
RegistryKey localMachine = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64); //here you specify where exactly you want your entry
var reg = localMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true);
if (reg == null)
{
reg = localMachine.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true);
}
if (reg.GetValue("EnableLinkedConnections") == null)
{
reg.SetValue("EnableLinkedConnections", "1", RegistryValueKind.DWord);
MessageBox.Show(
"Your configuration is now created,you have to restart your device to let app work perfektly");
}
}
I had the same issue. The reason of the problem: I was using as an Administrator. The mapped drives are related to the user, so I tried to use as an normal user and I could see the mapped drives.

UNC path is recognised as valid on an application deployed on most machines apart from two.

UNC path is recognised as valid on an application deployed on most machines apart from two. They have read or read/write permissions. How can I fix this?
It is the Directory Exists in C#:
For example, using a hypothetical UNC path #"\test server\test first folder\second folder\third folder\Final destination";
then with all but two users this code works:
bool exists;
if (textBox1.Text == string.Empty)
{
exists = false;
}
else
{
Directory.GetAccessControl(textBox1.Text);
exists = Directory.Exists(Path.GetDirectoryName(textBox1.Text));
// MessageBox.Show(exists.ToString(),"Directory", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//
// The user selected a folder and pressed the OK button.
// A message pops up and identifies the number of files found within that folder.
//
//textBox1.Text = f.FileName; //OpenFile dialog f FileName
if (textBox1.Text == string.Empty )
{
MessageBox.Show("No directory selected","Directory",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
else if (exists == false)
{
MessageBox.Show("Directory does not exist", "Directory", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
it finds the path (it is valid). But with the two users they get a "Path does not exist. Verify that the path is correct" error.
Any assistance greatly appreciated.
Thanks
Your code looks fine.
If you say it is working on most machines, most likely, the issue is not with your code but rather with your underlying network setup or the string you are entering in the textbox (keep in mind that a UNC path should always start with 2 backslashes).
As a suggestion you might try to access the UNC path trough explorer (assuming you're talking about Windows machines) on the two machines where your code is not working. If you can't access it this way, you're code won't be able to either.

FolderBrowserDialog apears in back in web application

I'm using FolderBrowserDialog on my web application in c#.
It is working perfectly except one issue:
the FolderBrowserDialog open in the back of the web application and not in front of it.
The code is:
public void BrowseFolderButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
}
}
for the second time the user click on the button it opens in the back.
Any help will be appriciate!
thanks,
Moran
FolderBrowserDialog will always popup at the Server side, the client/browser will never see it so client would hang there forever waiting for input...
In your case, both Client and Server on the same pc, this is why you saw the dialog working.
As far as I know there are no components from Microsoft that allow to browse the Folders on Client side. But you can always try open source Solutions...
for instance:
http://www.codeproject.com/Articles/21895/Directory-Browsing-in-ASP-Net-2-0

Access is denied in windows forms

Iam asking this question as a series to the below link
Unable to delete .exe file through c#
While i was debugging the application,iam able to delete the .exe file.But when i try to delete the application after installing in the desktop,again iam getting the exception message as "Access is denied".
Edit:-
The code i am using to delete the file
public bool deleteAppExecutable(string filePath)
{
try
{
if (File.Exists(filePath))
{
var di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
di.Attributes &= ~FileAttributes.ReadOnly;
SetAccessRule(filePath);
File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.ReadOnly);
File.Delete(filePath);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public static void SetAccessRule(string filePath)
{
FileInfo dInfo = new FileInfo(filePath);
FileSecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.Delete, AccessControlType.Allow));
dInfo.Refresh();
dInfo.SetAccessControl(dSecurity);
}
I found the solution why i am getting the "access is denied" exception in my application.
Since i am deleting a file inside the application through code i need to have the privilege of "Administrator".
One way is to make the user login manually as administrator.But that is not a better option.
Another way is to create an App Manifest file within your project and set the level as "administrator."
Creating App Manifest--> Right click on the project->Add new item-->Select App Manifest option from the right pane->Click ok
Open the manifest file and change the level to "requireAdministartor".
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This will solve the issue while running the application,it will prompt user to run as administrator.
Hope this will be helpful to someone in future. :)
Check that you have full permissions on the folder the exe is contained in (and all of it's child objects)

Directory.CreateDirectory access to path is denied?

I have server-client application, it's a file manager
my problem is when I go inside a folder which requires access control like system folders, it becomes to read-only, but I need to move/delete or create new folder, how can I get the permission to do that?
here's how I create a new folder at the server side
public void NewFolder(string path)
{
try
{
string name = #"\New Folder";
string current = name;
int i = 0;
while (Directory.Exists(path + current))
{
i++;
current = String.Format("{0} {1}", name, i);
}
Directory.CreateDirectory(path + current);
Explore(path); //this line is to refresh the items in the client side after creating the new folder
}
catch (Exception e)
{
sendInfo(e.Message, "error");
}
}
There are often directories on a drive that even a user with administrator privileges cannot access. A directory with a name like "HDDRecovery" is quite likely to be troublesome like this. Surely it contains sensitive data that helps the user recover from disk failure. Another directory that fits this category is "c:\system volume information", it contains restore point data.
An admin can change the permissions on folders like this. But of course that doesn't solve the real problem nor is it a wise thing to do. Your user can't and shouldn't. Be sure to write code that deals with permission problems like this, simply catch the IOExeption. Keep the user out of trouble by never showing a directory that has the Hidden or System attribute set. They are the "don't mess with me" attributes.
If you want to remove directory read-only attribute use this: http://social.msdn.microsoft.com/Forums/en/vblanguage/thread/cb75ea00-f9c1-41e5-ac8e-296c302827a4
If you want to access system folders you can run your program as local administrator.
I had a similar problem (asp.net MVC vs2017) with this code:
Directory.CreateDirectory("~/temp");
Here is my solution:
// Create path on your web server
System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~/temp"));
I also ran into an issue similar to this, but I was able to manually navigate through Windows Explorer and create directories.
However, my web app, running in VS on my laptop, hosted through my local IIS and not the built-in IIS deal for VS, was triggering the Access Denied issue.
So when I was hitting the error in code, I drilled down to glean more data from the System.Environment object and found the user, which of course was the App Pool that my app was running under in IIS.
So I opened IIS and opened the Advanced Settings for the app pool in question and changed the Identity to run under Network Service. Click OK. "cmd -> iisreset" for good measure. Try the app again, and SUCCESS!!!!
I had the same issue when creating a directory. I used DirectorySecurity as shown below:
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\AdminAccount1", FileSystemRights.Read, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\YourAppAllowedGroup", FileSystemRights.FullControl, AccessControlType.Allow));
DirectoryInfo di = Directory.CreateDirectory(path + current, securityRules);
Also keep in mind about the security as explained by Hans Passant's answer.
Full details can be found on MSDN.
So the complete code:
public void NewFolder(string path)
{
try
{
string name = #"\New Folder";
string current = name;
int i = 0;
while (Directory.Exists(path + current))
{
i++;
current = String.Format("{0} {1}", name, i);
}
//Directory.CreateDirectory(path + current);
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\AdminAccount1", FileSystemRights.Read, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\YourAppAllowedGroup", FileSystemRights.FullControl, AccessControlType.Allow));
DirectoryInfo di = Directory.CreateDirectory(path + current, securityRules);
Explore(path); //this line is to refresh the items in the client side after creating the new folder
}
catch (Exception e)
{
sendInfo(e.Message, "error");
}
}
My suspicion is that when you are running the application in client/server mode, the server portion needs to be running as Administrator, in addition to possibly removing read-only or system flags, to be able to do what you want.
That said, I agree with #HansPassant- it sounds like what you are trying to do is ill-advised.
Solved:
Directory created on remote server using below code & setting.
Share folder and give the full permission rights also in Advance
setting in the folder.
DirectoryInfo di = Directory.CreateDirectory(#"\\191.168.01.01\Test\Test1");
Test is destination folder where to create new Test1 folder(directory)

Categories