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)
Related
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.
I have a C# program which checks if a specific directory exists.
It is simply doing:
Directory.Exists(path).
I tried other ways as well. Using DirectoryInfo and using AlphaFS
On my local machine, the path exists. When I run the same program on a server with the same credentials it doesn't exist.
I wonder if it is a group policy issue. But I am able to go up one level and see it.
\server\volume\share\sub directory - Doesn't exist remotely but on my desktop it does
\server\volume\share - Does exist both on my desktop and remote server
Update
I forgot to mention, that since I had access to my desktop, I got the ACL information.
None of the groups were able to translate.
I really just want to get this application to behave the same way is on the server and find out why it is behaving differently.
Update 2
These are physical servers.
My desktop is Liquid VDI
Below is the code:
var path = txtPath.Text;
using (var user = new Impersonation(fuserdomain, fc_user, fc_pass))
{
var alphaExists = Alphaleonis.Win32.Filesystem.Directory.Exists(path);
var alphaDIExists = new Alphaleonis.Win32.Filesystem.DirectoryInfo(path).Exists;
var SystemExists = System.IO.Directory.Exists(path);
var SystemDIExists = new System.IO.DirectoryInfo(path).Exists;
var AlphaHasFiles = false;
var AlphaDIHasFiles = false;
var SystemHasFiles = false;
var SystemDIHasFiles = false;
try
{
Directory.GetFiles(path);
AlphaHasFiles = true;
}
catch { }
try
{
new DirectoryInfo(path).GetFiles();
AlphaDIHasFiles = true;
}
catch { }
try
{
System.IO.Directory.GetFiles(path);
SystemHasFiles = true;
}
catch { }
try
{
new System.IO.DirectoryInfo(path).GetFiles();
SystemDIHasFiles = true;
}
catch { }
MessageBox.Show(string.Format("alphaExists: {0}\nalphaDIExists: {1}\nSystemExists: {2}\nSystemDIExists: {3}\nAlphaGetFiles: {4}\nAlphaDIGetFiles: {5}\nSystemGetFiles: {6}\nSystemDIGetFiles: {7}\n", alphaExists, alphaDIExists, SystemExists, SystemDIExists, AlphaHasFiles, AlphaDIHasFiles, SystemHasFiles, SystemDIHasFiles));
}
Update 3
Although I have workaround this issue; I am still not sure why I would have a difference between my desktop and server. Is there any tool that can help me see where the issue may be?
I've seen the same thing with File.Exists. I never found an answer and finally threw in the towel, I simply try to use it and catch the exception.
Robust code has to catch it anyway, all the test does is avoid trying if the file or directory is not there. (And the PITA that Visual Studio no longer as any way to ignore an exception on a certain line. No problem runtime, annoying in development.)
This is a complete shot in the dark, since we don't have any specific details to go on. e.g. Is the server you're talking about physically yours, or is it a cloud-based server service?
I'd guess that your machine is an older operating system than the server, and the folder that you're trying to access is one of those special folders that has become more locked down with more recent operating systems (particularly on server operating systems) like the "Program Files" folder. So even though the folder exists on both, the method works on your machine but not on the server, due to permissions.
Hope this helps.
As far as I can tell, the Impersonation class in your code is not part of the dot net framework. Googling finds a couple of implementations. Where does it come from and How confident are you that it actually works in your scenario?
For example, if you remove the Impersonation code, and actually run it as that user, does that make it work?
One other clarification... When you say
\server\volume\share
Do you mean this is a network location (e.g. a UNC location), so is the same network path you are trying to access from both machines? If so, this would open up new possibilities for problems like firewalls, etc... Is that location on either of the two machines that we know about from the question, or a different location?
In my web application, i have some files those are saving within application it's creating a folder for saving files but i need to save those file outside of the application and inside of IIS.how can i do this?
With in application Folder we are using below code
Server.MapPath(Path)
For Saving in IIS How can i Write?
Thank you
you need to create a virtual directory that points ti the folder outside.
Go to IIS right click on your website. click on Add Virtual directry from the menu.Give an alias for the directory select your desired folder and you are done. it will consider this outside folder as an internal folder and work the same way. check this link How to: Create and Configure Virtual Directories in IIS 7.0
Disclaimer: but you will have to do this after hosting to iis i.e publishing. while using visual studio in dev environment i.e debugging it will store in internal directories only
Edit: for creating virtual directories this is the code. I have not tested its validity.
static void CreateVDir(string metabasePath, string vDirName, string physicalPath)
{
// metabasePath is of the form "IIS://<servername>/<service>/<siteID>/Root[/<vdir>]"
// for example "IIS://localhost/W3SVC/1/Root"
// vDirName is of the form "<name>", for example, "MyNewVDir"
// physicalPath is of the form "<drive>:\<path>", for example,"C:\Inetpub\Wwwroot"
try
{
DirectoryEntry site = new DirectoryEntry(metabasePath);
string className = site.SchemaClassName.ToString();
if ((className.EndsWith("Server")) || (className.EndsWith("VirtualDir")))
{
DirectoryEntries vdirs = site.Children;
DirectoryEntry newVDir = vdirs.Add(vDirName, (className.Replace("Service", "VirtualDir")));
newVDir.Properties["Path"][0] = physicalPath;
newVDir.Properties["AccessScript"][0] = true;
// These properties are necessary for an application to be created.
newVDir.Properties["AppFriendlyName"][0] = vDirName;
newVDir.Properties["AppIsolated"][0] = "1";
newVDir.Properties["AppRoot"][0] = "/LM" + metabasePath.Substring(metabasePath.IndexOf("/", ("IIS://".Length)));
newVDir.CommitChanges();
}
else
}
catch (Exception ex)
{
}
}
Normally you can not create a folder outside the root path i.e. if you have your application in say C:\inetpub\testapp you can only create a folder inside testapp. This restriction is for security reason where a web server is not supposed to allow access to anything above root folder.
Moreover it's not recommended to write any folders/files in the root folder as writing to root folder cause appdomain to recycle after certain number of writes (default is 15) causing session loss. See my answer here.
However there is a workaround
Add a path of your server to web.config and then fetch it in your code.Use something like below in the appsettings section of web.config
<add key="logfilesPath" value="C:\inetpub\MyAppLogs" />
Create a folder of above path and add Users group to your folder and give that group full permission (read/write). (Adding permission is very important)
In your code you can fetch as below
string loggerPath = (ConfigurationManager.AppSettings["logfilesPath"]);
Hope this helps
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)
i write the code in asp.net using c# to delete the file in my computer, but it is not deleting please help me thank u. this is my code, i write in button click event
string path = "E:\\sasi\\delt.doc";
FileInfo myfileinf = new FileInfo(path);
myfileinf.Delete();
public void DeleteFileFromFolder(string StrFilename)
{
string strPhysicalFolder = Server.MapPath("..\\");
string strFileFullPath = strPhysicalFolder + StrFilename;
if (IO.File.Exists(strFileFullPath)) {
IO.File.Delete(strFileFullPath);
}
}
In order to delete a file you must ensure that the account has sufficient permissions. In general ASP.NET applications run under limited permission account such as Network Service. For example if your application runs under IIS 6 you could go to the Administration Console and set a custom account in the application pool properties:
alt text http://i.msdn.microsoft.com/Bb969101.SharePoint_SQL_TshootingFig3%28en-US,SQL.90%29.jpg
You need to ensure that the account is member of the IIS_WPG group.
Make sure the ASP user has permissions to this folder. By default this user is not given access to much of the harddrive..