Folder Rename using Directory.Move(): Access to Path is Denied - c#

I have Common Network Shared Folder When Folder Rename using Directory. Move(): Access to Path is Denied, Actual Problem is When Folder is open by another System or another process, If Any possible to rename the folder or Close the Folder Open by another system or another process
My Code
static void moveToShare()
{
if (!Directory.Exists("\\Share")) Directory.CreateDirectory("\\Share");
string timestamp = DateTime.Now.ToString("yyyyMMddHHmms");
try
{
Directory.Move("\\Output", "\\Share\\" + timestamp);
}
catch(Exception e)
{
Console.WriteLine("Cant Move Folder: " + e.Message);
}
}

You must gain access.
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsIdentity idnt = new WindowsIdentity(username, password);
WindowsImpersonationContext context = idnt.Impersonate();
if (!Directory.Exists("\\Share"))
Directory.CreateDirectory("\\Share");
string timestamp = DateTime.Now.ToString("yyyyMMddHHmms");
try
{
Directory.Move("\\Output", "\\Share\\" + timestamp);
}
catch(Exception e)
{
Console.WriteLine("Cant Move Folder: " + e.Message);
}
context.Undo();

Related

C# Windows Service Not Compressing Folder Correctly

Im currently building a Windows service that will be used to create backups of logs. Currently, the logs are stored at the path E:\Logs and intent is to copy the contents, timestamp their new folder and compress it. After this, you should have E:\Logs and E:\Logs_[Timestamp].zip. The zip will be moved to C:\Backups\ for later processing. Currently, I am using the following to try and zip the log folder:
var logDirectory = "E://Logs";
var timeStamp = DateTime.Now.ToString("yyyyMMddHHmm");
var zippedFolder = logDirectory + "_" + timeStamp + ".zip";
System.IO.Compression.ZipFile.CreateFromDirectory(logDirectory, zippedFolder);
While this appears to create a zip folder, I get the error Windows cannot open the folder. The Compressed (zipped) Folder E:\Logs_201805161035.zip is invalid.
To address any troubleshooting issues, the service is running with an AD account that has a sufficient permission level to perform administrative tasks. Another thing to consider is that the service kicks off when its FileSystemWatcher detects a new zip folder in the path C:\Aggregate. Since there are many zip folders that are added to C:\Aggregate at once, the FileSystemWatcher creates a new Task for each zip found. You can see how this works in the following:
private void FileFoundInDrops(object sender, FileSystemEventArgs e)
{
var aggregatePath = new DirectoryInfo("C://Aggregate");
if (e.FullPath.Contains(".zip"))
{
Task task = Task.Factory.StartNew(() =>
{
try
{
var logDirectory = "E://Logs";
var timeStamp = DateTime.Now.ToString("yyyyMMddHHmm");
var zippedFolder = logDirectory + "_" + timeStamp + ".zip";
ZipFile.CreateFromDirectory(logDirectory, zippedFolder);
}
catch (Exception ex)
{
Log.WriteLine(System.DateTime.Now.ToString() + " - ERROR: " + ex);
}
});
task.Dispose();
}
}
How can I get around the error I am receiving? Any help would be appreciated!

Create a remote directory c# using full control permissions. UnauthorizedAccessException: Access to Path Denied even using security rules

Hope you are well!
Thanks for reading my issue.
I´m trying to create a remote directory using spcefic credentials as Administrator, and also I checked Full Control Premission on the root directory in the seurity tab.
I'm running the program as the Administrator.
This Exception occurs when I try to create a Direcotry / Subdirectories.
But, when I create a File, it really works! (only when the path exists).
Using [File.WriteAllBytes(path, bytes_array);].
If the path doesn´t exist the Exception occurs too.
As an aside, I'm using PinvokeWindowsNetworking Class: http://lookfwd.doitforme.gr/blog/media/PinvokeWindowsNetworking.cs
This is my code:
static void Main(string[] args)
{
// Specify the directory you want to manipulate.
try
{
PinvokeWindowsNetworking.connectToRemote(#"\\PC-NAME\MyDocuments", "Administrator", "MyPa$$");
string path = #"R:\Recursos\ControlDocumentos\DIR\DIR1";
string sRutaDestinoNva = path.Replace(#"R:", #"\\PC-NAME\MyDocuments");
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(#"\Administrator", FileSystemRights.FullControl, AccessControlType.Allow));
if (Directory.Exists(sRutaDestinoNva))
{
Console.WriteLine("Path is already exists");
}
else
{
Directory.CreateDirectory(sRutaDestinoNva, securityRules);
Console.WriteLine("Directory and Subdirectories were creted succesfully: " + Directory.GetCreationTime(sRutaDestinoNva).ToString());
}
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
Console.ReadKey();
}
finally { PinvokeWindowsNetworking.disconnectRemote("\\\\PC-NAME\MyDocuments"); }
}
Exception Image
I appreciate your help so much!

Access to the path is denied from get assembly version of file

I create web form application to upload file (.exe) and i get assembly version of file but i have a problem is 'access to the path is denied' when i am deleting file after get version.
Code :
protected void uploadBT_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
/** Save file to tmp **/
string filename = FileUpload1.PostedFile.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/FilesUploaded/tmp/" + filename));
/** get assembly version **/
Assembly asb = Assembly.LoadFile(Server.MapPath("~/FilesUploaded/tmp/" + filename));
string version = asb.GetName().Version.ToString();
Directory.Delete(Server.MapPath("~/FilesUploaded/tmp"), true);
Thread.Sleep(5);
Directory.CreateDirectory(Server.MapPath("~/FilesUploaded/tmp"));
/** Save each versions **/
Directory.CreateDirectory(Server.MapPath("~/FilesUploaded/" + version));
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/FilesUploaded/" + version + "/" + filename));
}
catch (Exception ex)
{
errTxt.Text = ex.Message.ToString();
}
}
}
IIS most likely blocking .exe, you'd need to allow it through the MIME types.
The hosting company should be able to grant the permissions to that folder to aspnet user since it appears that is your hosted directory but I could be wrong. Have you asked their support about this error?

Directory.CreateDirectory(Path) does not create the given folder

This code is running in a ASP Page.
try
{
DirectoryInfo di = Directory.CreateDirectory(destDir);
DirectoryInfo diOut = Directory.CreateDirectory(destDir + "\\output");
if (di.Exists)
{
ErrorLog(Server.MapPath("Logs/ErrorLog"),"created or existing destDir: " + destDir );
}
if (diOut.Exists)
{
ErrorLog(Server.MapPath("Logs/ErrorLog"),"created or existing outputDir:" + destDir +"\\output" );
}
}
catch(Exception e)
{
ErrorLog(Server.MapPath("Logs/ErrorLog"),"caught error: " + e.ToString() );
}
The value of dst dir is:
d:\foo-server\THE\jobgenerator\xmlinput\tmp_JobGenerator_09_08_201216_09_21_718374_THE
The parent folder d:\foo-server\THE\jobgenerator\xmlinput already exists.
The log output says that the destDir has been created but when I check the folder I can see that there has been nothing created. The Site is running on a IIS, the configured user has full permission on the parent folder.
I dont understand why the di.Exists results in true even if the folder has not been created. Also no Exception will be thrown.
Thanks for the help.

Trouble deleting a file from c:\windows\system32 using C#

Not quite sure why I can't get this file to delete. I'm logged in as Admin, tried "Run as Admin", tried running in the same folder, tried setting permissions on the file, tried creating a test 1.txt file to delete and no luck. It is acting like the file isn't there. I can see it in Windows Explorer. Please any help is welcome. Thank you for your time.
public void deleteFile(string FileToDelete)
{
//sets system32 to system32 path
string system32 = Environment.SystemDirectory + #"\";
//File.SetAttributes(#system32 + FileToDelete, FileAttributes.Normal);
try
{
//check if file exists
if (!File.Exists(#system32 + #FileToDelete))
{
//if it doesn't no need to delete it
Console.WriteLine("File doesn't exist or is has already been deleted.");
//Console.WriteLine(system32 + FileToDelete);
} //end if
//if it does, then delete
else
{
File.Delete(system32 + FileToDelete);
Console.WriteLine(FileToDelete + " has been deleted.");
} //end else
} //end try
//catch any exceptions
catch (Exception ex)
{
Console.WriteLine(Convert.ToString(ex));
} //end catch
} //end DeleteFile
I created a test file "test.txt" and it worked no problem. I should not that I didn't use the method you posted, but rather used the contents of your supplied method and used them within the main() method of a console application.
ou should also add ReadLine() to display any messages that are returned.
This is what I used, not that it's much different from what you supplied. If this code doesn't work for you then it must be a system privileged issue.
static void Main(string[] args)
{
string FileToDelete = "test.txt";
//sets system32 to system32 path
string system32 = Environment.SystemDirectory + #"\";
try
{
//check if file exists
if (!File.Exists(system32 + FileToDelete))
{
//if it doesn't no need to delete it
Console.WriteLine("File doesn't exist or is has already been deleted.");
//Console.WriteLine(system32 + FileToDelete);
Console.ReadLine();
} //end if
//if it does, then delete
else
{
File.Delete(system32 + FileToDelete);
Console.WriteLine(FileToDelete + " has been deleted.");
Console.ReadLine();
} //end else
} //end try
//catch any exceptions
catch (Exception ex)
{
Console.WriteLine(Convert.ToString(ex));
Console.ReadLine();
} //end catch
}
Try this one out
check if file exist on 64 bits system using File.Exists
If you're using Vista / Windows 7, maybe you're running into file virtualization issues. Have you tried adding a manifest with a <requestedExecutionLevel level="requireAdministrator"/> line in it ?

Categories