Why is access denied when I try to move a directory? - c#

I have two directories: folder1 and folder2. folder1 contains a file. I'd like to move folder1 under folder2 to result in folder2\folder1. When I try to do this with the C# code below, I get:
System.IO.IOException: Access to the path 'E:\www\dev\test\MoveDirectories\folder1' is denied.
The relevant code:
// In Page_Load.
MoveDirectory("folder1");
// Method for moving directories.
protected void MoveDirectory(string strMoveThis)
{
try
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Server.MapPath(strMoveThis));
dir.MoveTo(Server.MapPath("\\folder2\\"));
}
catch (Exception ex)
{
Response.Write(ex);
}
}
My ASP.NET 4.0 app pool has modify privileges on the folder1. This is actually a test application with code that has been pulled from a much bigger application, so it doesn't have all of the testing and exception handling one would expect.
EDIT: I found that I can create files within folder1.

I hate to answer my own question, but...
Basically, I updated this:
dir.MoveTo(Server.MapPath("\\folder2\\"));
to this:
dir.MoveTo(Server.MapPath("folder2\\" + strMoveThis));
Same permissions, but a better formation of the path. Thanks for your help, everyone!

Related

Copying files into newly created folder giving error "its being used by another process

I try to create a sub-application that copies the database to the user desired location. Although an error is popping up that my newly created folder is being used by another application (i havent used any stream readers).
The files are correct and the copy to the selected directory is totaly working , although the problem starts when i create the folder and after i try to use him.
//Snippet
string SourceFile1 = #"C:\Users\user\Documents\DLLTESTBASE.mdf";
string SourceFile2 = #"C:\Users\user\Documents\DLLTESTBASE_log.ldf";
string BackupDirectory = BackupLocation.SelectedPath + "\\" + BackupName;
if (!Directory.Exists(BackupDirectory)){
Directory.CreateDirectory(BackupDirectory);
}
else{
MessageBox.Show("A copy has been found :\n" + BackupDirectory , "Copy has been stoped!");
}
string targetPath1 = BackupDirectory + "\\DB.mdf";
string targetPath2 = BackupDirectory + "\\DB_log.ldf";
try{
System.IO.File.Copy(SourceFile1, targetPath1);
System.IO.File.Copy(SourceFile2, targetPath2);
MessageBox.Show("Copy has been successful.", "Completed!");
}
catch (Exception ex){
MessageBox.Show("An error has been occured."+ex,"Operation failed!");}
}
The result must be that the 2 files will be inside of the folder.
Sql Data Base File in use with Sql Service
Goto Services
Stop "Sql Server" Service
you can use this link stop-or-start-sql-server-service
If u dont want to stop service use this link
Also u can use Attaching-and-Detach DB PragmaticallyAttaching-and-Detach
Try the following line before you create the files:
File.SetAttribute(targetpath1, FileAttribute.Normal);
You will get an exception thrown if the files already exist.
You will need to either delete the files and then write to them or use overwrite parameter:
System.IO.File.Copy(sourcefile1, targetPath1, true);
Sorry for late responce, as it seem the problem was occuring beacause of a hidden compartment of my main application, the problem solved after restarting my computer and reappeared when i runned the main application so you were right guys that sql file-connection was running (although it wasnt visible).
Thank you everyone for the help ☺

How can i save files in folder within the IIS of outside of the Application folder in asp.net

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

C#, Creating .txt file

I am having trouble creating a .txt file with the code below. I get an exception as follows:
Unhandled exception: System.unauthorizedAccessException: Access to the
path 'C:\log.txt' is denied.
I have looked online and done similar things to what is on the api. Below is my code, so you can understand what my train of logic is. What do you think causes this exception? Thanks in advance!
static StreamWriter swt;
static string logFile = #"C:\log.txt";
static FileStream fs;
static void Main(string[] args)
{
Console.Out.WriteLine(swt);
string root = args[0];
if (!File.Exists(logFile))
{
try
{
fs = File.Create(logFile);
}
catch (Exception ex)
{
swt.WriteLine("EXCEPTION HAS BEEN THROWN:\n " + ex + "\n");
}
{
}
}
}
You're most likely getting this error because a standard user cannot write to the root of a drive without elevated permissions. See here.
Detect the folder permissions. It has to has write permission on the logged user.
Yes, it is permission error. You don't have enough rights to write file in C: drive. To write in these types of folder/drive you need admin permission.
You can give your application admin rights. Simple way is enforce your application to start in admin account/rights only. To achieve this
Solution Explorer -> your project -> Add new item (right click) -> Application Manifest File.
In this file change requestedExecutionLevel to
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
These enforce your application with admin rights only. On Windows 8/7/Vista it will display UAC (User Access Control) dialog box when you start the application.
Hope this will help you....

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)

Remove Read-Only Attribute On FOLDER On A Network Share

I am having an issue that is really killing me.
I have a directory that when I go to the properties window, shows Read-Only as partially checked (not a full check box, but the box is filled).
So I looked in the directory and I checked all the files, none of them have the read-only attribute. Only the folder has it, and only partially.
I tried the following code:
if (directoryInfo.Exists)
{
try
{
directoryInfo.Attributes &= ~FileAttributes.ReadOnly;
foreach (FileInfo f in directoryInfo.GetFiles())
{
f.IsReadOnly = false;
}
}
catch (Exception e)
{
throw e;
}
}
It still did not work. I can right click on the folder and manually remove the read-only permissions but I need to be able to do this in code. The code executes but does not error.
Anyone have any idea what the issue could be? My only guess is because the folder is on a network share (in the form of \\computer\folder\subfolder), that I might need special rights in order to change permissions on a folder?
Please someone help.
Thanks in advance
readonly on folders is used by Windows internally... if you really need to change it then is some work involved (Registry and changing alot of folders)... see http://support.microsoft.com/kb/256614/en-us
Why do you need to make that change ?
EDIT - some information on Powershell and TFS:
http://codesmartnothard.com/ExecutingPowerShellScriptsOnRemoteMachinesWithTFS2010AndTeamDeploy2010.aspx
http://blogs.msdn.com/b/yao/archive/2011/06/15/tfs-integration-pack-and-scripting-using-powershell.aspx
or try a normal "batch file" (.bat) with "attrib -r" on the folder

Categories