Alright, I've seen tons of questions about this thing, but still, no one answers my question. In fact, each one of the questions I saw differs from the other, this access thing really seems to be hassling programmers.
Please check out the code:
DirectoryInfo Dir1 = Directory.CreateDirectory(Desktop + "\\DIR1");
DirectoryInfo Dir2 = Directory.CreateDirectory(Desktop + "\\DIR2");
//* Lets Create a couple of SubDirs in DIR1
for (int i = 0; i < 5; i++)
{
// this will create 5 SubDirs in DIR1, named Sub1, Sub2 ... Sub5.
Dir1.CreateSubdirectory("Sub" + (i + 1).ToString());
//* lets create 5 text files in each SubDir:
for (int j = 0; j < 5; j++)
{
File.Create(Dir1.FullName + "\\Sub"+(i+1).ToString() + "\\text"+(j+1).ToString() + ".txt");
}
}
//* Lets Move all what we created in DIR1 to DIR2 (THIS IS WHERE I'M GETTING THE EXCEPTION
Directory.Move(Dir1.FullName, Dir2.FullName + "\\DIR1");
// I also Tried Dir1.MoveTo(Dir2.FullName + "\\DIR1");
Stack Trace:
at System.IO.DirectoryInfo.MoveTo(String destDirName)
at Directory_Class.Program.Main(String[] args) in c:\users\vexe\documents\visual studio 2010\Projects\Directory_Class\Directory_Class\Program.cs:line 207
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
And of course, I tried the usual:
DirectorySecurity DirSec = Dir1.GetAccessControl();
string user = Environment.UserName;
DirSec.ResetAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl, AccessControlType.Allow));
Dir1.SetAccessControl(DirSec);
But it didn't change a bit!
I also tried changing the permissions manually, by right clicking dir1 -> properties -> security -> edit -> add -> typed everyone (in the enter object names to select) -> ok -> fullcontrol to everyone. (I also saw that my user account had full control as well)
Any hints would be deeply appreciated
While it is an Access Denied exception, it sounds like the text files are in use and cannot be moved because there are open references to the file.
The File.Create method returns a FileStream object which I'd imagine must be closed/disposed before the files can be modified.
Try the following for your inner loop:
for (int j = 0; j < 5; j++)
{
using(var fs = File.Create(Dir1.FullName + "\\Sub"+(i+1).ToString() + "\\text"+(j+1).ToString() + ".txt"))
{
//fs.WriteByte(...);
fs.Close();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With