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.
Related
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();
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!
I have a root directory with a path defined as
string MyPath = #"D:/Documents/Reonance Tunneling";
I have a delete method that will delete any selected sub-directory written as follows:
private void BntDeleteFolder_Click(object sender, EventArgs e)
{
TreeNode newSelected = TreeView1.SelectedNode;
string DirectoryName = newSelected.Text;
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
try
{
if (MessageBox.Show("Are you sure you want to delete Folder " + "'" + DirectoryName + "'" + " ?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
foreach (FileInfo file in nodeDirInfo.GetFiles())
{
File.Delete(MyPath + "//" + DirectoryName + "//" + item.Text);
}
Directory.Delete(MyPath + "//" + DirectoryName + "//");
newSelected.Remove();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
However if I try to delete any selected sub-directory of the sub-directory I get the following error: "Could not find part of the path... " or "The directory is not empty." Can anybody tell me how to fix this problem?
You are recreating plenty of ListViewItems that are never used (as Scott Chamberlain pointed out).
You already have a FileInfo instance. Simply use: FileInfo.Delete Method () on file.
and when you are done use nodeDirInfo.Delete() as well. You should probably also check for Subdirectories, not only files.
If you insist on using the static Directory - class, use Directory.Delete(nodeDirInfo.Fullname, recursive: true);
nodeDirInfo can delete all it files and directories (https://msdn.microsoft.com/en-us/library/c66e2tts(v=vs.110).aspx)
nodeDirInfo.Delete(true);
If you look at the documentation for the DirectoryInfo.Delete Method, you'll notice that it takes a bool that defines if it should also delete the subdirectories and all files in the directory. This is probably the easiest way to get around the "The directory is not empty" exception.
To avoid the "Directory not found" exception, you can just check for it first:
var fullPath = Path.Combine(MyPath, newSelected.Tag);
if (Directory.Exists(fullPath))
{
new DirectoryInfo(fullPath).Delete(true);
}
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!
I have a sync software, which loads CSV files from "Incoming" folder, processes them and then moves them to the "Archive" folder.
Today, I saw the following error with this sync software:
[23/06/2014 00:06:04 AM] : Failed to move file from
D:\IBI_ORDER_IMPORTER_FTP_SERVER\Template3\Fifty &
Dean\Incoming\5A040K___d6f1ca45937b4ceb98d29d0db4601bf4.csv to
D:\IBI_ORDER_IMPORTER_FTP_SERVER\Template3\Fifty &
Dean\Archive\5A040K___d6f1ca45937b4ceb98d29d0db4601bf4.csv - Could not
find a part of the path.
Here's a snippet taken out of the sync software, where the file is processed and moved:
public static void ProcessSingleUserFile(Int32 TemplateId, String ImportedBy, String FilePath)
{
// Always Rename File To Avoid Conflict
string FileName = Path.GetFileNameWithoutExtension(FilePath);
String NewFilePath = FilePath.Replace(FileName, Utils.RandomString() + "___" + FileName);
File.Move(FilePath, NewFilePath);
FilePath = NewFilePath;
// Log
SyncUtils.ConsoleLog(String.Format("Processing [ {0} as {1} ] By [ {2} ] On Template [ #{3} ]",
FileName + ".csv",
Path.GetFileName(FilePath),
ImportedBy,
TemplateId));
// Init
List<OrderDraft> myOrderDrafts = new List<OrderDraft>();
// Parsed Based On Template Id
if (TemplateId == Settings.Default.Multi_Order_Template_Id)
{
// Try Parse File
myOrderDrafts = Utils.ParseMultiImportFile(TemplateId, ImportedBy, FilePath, true);
}
else
{
// Try Parse File
myOrderDrafts.Add(Utils.ParseImportFile(TemplateId, ImportedBy, FilePath, true));
}
// Process Orders
foreach (OrderDraft myOrderDraft in myOrderDrafts)
{
/* code snipped */
}
// Archive File
File.Move(FilePath, FilePath.Replace("Incoming", "Archive"));
}
Any idea what this error means? and how to circumvent it?
I wrote a cut down version of the above to test this in a controlled environment and I am not getting the error with this code:
static void Main(string[] args)
{
try
{
string baseDir = #"C:\Users\Administrator\Desktop\FTP_SERVER\Template3\Fifty & Dean\Incoming\";
string[] filePaths = Directory.GetFiles(baseDir, "*.csv");
foreach (string filePath in filePaths)
{
// do some work here ...
// move file
string newFilePath = filePath.Replace("Incoming", "Archive");
File.Move(filePath, newFilePath);
Console.WriteLine("File successfully moved");
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Console.ReadKey();
}
You need to include the checks to make sure that the paths exist at runtime and check the output, something very simple like:
if(!Directory.Exists(Path.GetDirectoryName(filePath)))
{
Console.WriteLine("filePath does not exist: " + filePath);
}
if(!Directory.Exists(Path.GetDirectoryName(newFilePath)))
{
Console.WriteLine("newFilePath does not exist: " + newFilePath);
}
File.Move(filePath, newFilePath);
The reason I am suggesting this method is due to a possibility that the paths momentarily become available or not under the multi-tasking OSs depending on a multitude of factors: network connectivity, permissions (pushed down by GPO at any time), firewall rules, AV exclusions getting blown away etc. Even running low on CPU or RAM may create issues. In short, you never know what exactly occurred when your code was running if you are only checking the paths availability after the fact.
Or if your issue is intermittent, you can try and catch the error and write information to some sort of a log similarly to below:
try
{
File.Move(filePath, newFilePath);
}
catch(Exception ex)
{
if(!Directory.Exists(Path.GetDirectoryName(filePath)))
{
Console.WriteLine("filePath does not exist: " + filePath);
}
if(!Directory.Exists(Path.GetDirectoryName(newFilePath)))
{
Console.WriteLine("newFilePath does not exist: " + newFilePath);
}
}
"Could not find a part of the path" exception could also thrown from File.Move if argument used was longer than MAX_PATH (260) in .NET Framework.
So I prepend the path I used with long path syntax before passing to File.Move and it worked.
// Prepend long file path support
if( !packageFile.StartsWith( #"\\?\" ) )
packageFile = #"\\?\" + packageFile;
See:
How to deal with files with a name longer than 259 characters?
I have this
Could not find a part of the path
happened to me when I
File.Move(mapfile_path , Path.Combine(newPath, mapFile));
. After some testing, I find out our server administrator has blocked any user application from writing to that directory in that [newPath]!
So, right click on that directory to observe the rights matrix on Security tab to see anything that would block you.
Another cause of DirectoryNotFoundException "could not find a part of the path" thrown by File.Move can be spaces at the end of the directory name. Consider the following code:
string destinationPath = "C:\\Folder1 "; //note the space on the end
string destinationFileNameAndPath = Path.Combine(destinationPath, "file.txt");
if (!Directory.Exists(destinationPath))
Directory.CreateDirectory(destinationPath);
File.Move(sourceFileNameAndPath, destinationFileNameAndPath);
You may expect this code to succeed, since it creates the destination directory if it doesn't already exist, but Directory.CreateDirectory seems to trim the extra space on the end of the directory name, whereas File.Move does not and gives the above exception.
In this circumstance, you can workaround this by trimming the extra space yourself, e.g. (depending on how you load your path variable, the below is obviously overkill for a hard-coded string)
string destinationPath = "C:\\Folder1 ".Trim();