Unhandled DirectoryNotFound exception thrown using DirectoryInfo.EnumerateFiles and "subst" command - c#

Background:
I'm trying to write a little program that recursively goes through all files contained in a user specified folder (and all its subfolders). The program is supposed to check the size of each file and if it matches a user defined value, copy their full path (File.FullName) to a text box control I've setup on the only form of the program.
The trouble is that because of the intended use of the program (working with recovered files and folders from damaged partitions on external drives), often the path length goes well over the maximum path length limit. In order to marginally circumvent this I decided to map the user selected starting directory to a virtual drive using the Win32 command line function "subst".
Incriminated Code:
private void button1_Click(object sender, EventArgs e)
{
if (txtboxSizeFilter.Text != "")//code will execute only if a size filter has been provided by the user
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
List<char> driveLetters = new List<char>(26); // Allocate space for alphabet
for (int i = 65; i < 91; i++) // increment from ASCII values for A-Z
{
driveLetters.Add(Convert.ToChar(i)); // Add uppercase letters to possible drive letters
}
foreach (string drive in Directory.GetLogicalDrives())
{
driveLetters.Remove(drive[0]); // removed used drive letters from possible drive letters
}
GlobalVars.Drive = driveLetters[0].ToString() + ":"; //gets the next available drive letter to be used as the virtual drive and adds a convenient ":" at the end
string command = "subst " + GlobalVars.Drive + " " + "\"" + folderBrowserDialog1.SelectedPath.ToString() + "\""; //command to be passed to "cmd". Ex. Content= subst J: "C:\users\someuser\somelongnamefolder\some longer name folder with spaces"
System.Diagnostics.Process.Start("cmd.exe", #"/c " + command);//launches the command prompt and initiates subst. This section has been tested and works fine.
DirectoryInfo DI = new DirectoryInfo(GlobalVars.Drive);//here i start at the drive letter that points to the desired directory.
foreach (var fi in DI.EnumerateFiles("*", SearchOption.AllDirectories))//searches for any file in all dirs. THE EXCEPTION "DirectoryNotFound" OBJECT OF THIS QUESTION IS THROWN EXACTLY HERE.
{
try //I need this because I might throw a PathTooLongException despite my use of subst
{
if (fi.Length == Convert.ToInt64(txtboxSizeFilter.Text))//if the size of the file is = to target size then I add the full path name to the textbox along with its actual size (for debug purposes only).
{
txtboxResults2Confirm.Text = txtboxResults2Confirm.Text + fi.FullName.ToString() + "_" + fi.Length.ToString() + Environment.NewLine;
}
}
catch (PathTooLongException)//if the path is too long, indicate it with the codeword "SKIP"
{
txtboxResults2Confirm.Text = txtboxResults2Confirm.Text + "SKIP" + Environment.NewLine;
}
}
btnConfirm.Enabled = true;//enables the other button on the form that will actually delete the files.
}
}
else
{
MessageBox.Show("INPUT SIZE FIRST!");
}
}
Problem/Research/Question:
As specified in the comments and the tile, an unhandled DirectoryNotFound exception occurs at the second foreach statement (as indicated by the IDE, Microsoft Visual Studio Ultimate 2013). Doing a step by step debug indicates that the foreach loop actually works for a while and then "randomly" throws the exception. I was able to verify that it goes through all the files in the root directory and at least a large part of the first subdirectory without any trouble at all (because of the large amount of files/subdirectories I wasn't able to pinpoint where exactly the failure occurs). The error states that the directory not found is the root one (so, to follow the example in the comments: "Unable to find J:\"). I've tried to follow the first catch with another to handle the DirectoryNotFound exception to not avail, which makes sense since the exception seems to originate directly in the foreach statement. I've also tried to wrap the entire foreach statement into a try-catch framework without any luck. Finally, getting rid of the whole "subst" section and just working with the user selected path produces no such error.
My question is, why is the exception thrown? And why am I not able to handle it in any way? Is there an alternate approach to this problem that would ensure the avoidance of the DirectoryNotFound exception?

The Process.Start does exactly that: it starts a new process (with its own main thread, etc etc) which may or may not complete by the time your next line of code in the original program executes. A couple of ways to resolve this: a) call DefineDosDevice which will mean the "subst" command runs in the current program thread, or b) grab the pipe to the cmd process and listen on it for completion. Both are of intermediate difficulty, pick your poison.
Of course, the exception that you're experiencing is because the subst command didn't complete in time when the code to enumerate the (yet un-aliased) directory executes.

Related

.NET File Access Violation

I feel kind of stupid posting this, but it seems like a genuine issue that I've made sufficiently simple so as to demonstrate that it should not fail. As part of my work I am responsible for maintaining build systems that take files under version control, and copy them to other locations. Sounds simple, but I've constantly experienced file access violations when attempting to copy files that I've supposedly already set as 'Normal'.
The code sample below simply creates a set of test files, makes them read only, and then copies them over to another folder. If the files already exist in the destination folder, the RO attribute is cleared so that the file copy will not fail.
The code works to a point, but at seemingly random points an exception is thrown when the file copy is attempted. The code is all single threaded, so unless .NET is doing something under the hood that causes a delay on the setting of attributes I can't really explain the problem.
If anyone can explain why this is happening I'd be interested. I'm not looking for a solution unless there is something I am definitely doing wrong, as I've handled the issue already, I'm just curious as no one else seems to have reported anything related to this.
After a few iterations I get something like:
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: Access to the path 'C:\TempFolderB\TEMPFILENAME8903.txt' is denied.
One other fact, if you get the file attributes BEFORE the file copy, the resulting state says the file attributes indeed Normal, yet examination of the local file shows it as Read Only.
/// <summary>
/// Test copying multiple files from one folder to another while resetting RO attr
/// </summary>
static void MultiFileCopyTest()
{
/// Temp folders for our test files
string folderA = #"C:\TempFolderA";
string folderB = #"C:\TempFolderB";
/// Number of files to create
const int fileCount = 10000;
/// If the test folders do not exist populate them with some test files
if (System.IO.Directory.Exists(folderA) == false)
{
const int bufferSize = 32768;
System.IO.Directory.CreateDirectory(folderA);
System.IO.Directory.CreateDirectory(folderB);
byte[] tempBuffer = new byte[bufferSize];
/// Create a bunch of files and make them all Read Only
for (int i = 0; i < fileCount; i++)
{
string filename = folderA + "\\" + "TEMPFILENAME" + i.ToString() + ".txt";
if (System.IO.File.Exists(filename) == false)
{
System.IO.FileStream str = System.IO.File.Create(filename);
str.Write(tempBuffer, 0, bufferSize);
str.Close();
}
/// Ensure files are Read Only
System.IO.File.SetAttributes(filename, System.IO.FileAttributes.ReadOnly);
}
}
/// Number of iterations around the folders
const int maxIterations = 100;
for (int idx = 0; idx < maxIterations; idx++)
{
Console.WriteLine("Iteration {0}", idx);
/// Loop for copying all files after resetting the RO attribute
for (int i = 0; i < fileCount; i++)
{
string filenameA = folderA + "\\" + "TEMPFILENAME" + i.ToString() + ".txt";
string filenameB = folderB + "\\" + "TEMPFILENAME" + i.ToString() + ".txt";
try
{
if (System.IO.File.Exists(filenameB) == true)
{
System.IO.File.SetAttributes(filenameB, System.IO.FileAttributes.Normal);
}
System.IO.File.Copy(filenameA, filenameB, true);
}
catch (System.UnauthorizedAccessException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
(This isn't a full answer, but I don't have enough reputation yet to post comments...)
I don't think you are doing anything wrong, when I run your test code I can reproduce the problem every time. I have never got past 10 iterations without the error occurring.
I did a further test, which might shed some light on the issue:
I set all of the files in TempFolderA to hidden.
I then ensured all of the files in TempFolderB were NOT hidden.
I put a break-point on Console.WriteLine(ex.Message)
I ran the code, if it got past iteration 1 then I stopped, reset the hidden attributes and ran again.
After a couple of tries, I got a failure in the 1st iteration so I opened Windows Explorer on TempFolderB and scrolled down to the problematic file.
The file was 0 bytes in size, but had RHA attributes set.
Unfortunately I have no idea why this is. Process Monitor doesn't show any other activity which could be relevant.
Well, right in the documentation for the System.IO.File.SetAttributes(string path, System.IO.FileAttributes attributes) method, I found the following:
Exceptions:
System.UnauthorizedException:
path specified a file that is read-only.
-or- This operation is not supported on the current platform.
-or- The caller does not have the required permission.
So, if I had to guess, the file in the destination (e.g. filenameB) did in fact already exist. It was marked Read-Only, and so, the exception was thrown as per the documentation above.
Instead, what you need to do is remove the Read-Only attribute via an inverse bit mask:
if (FileExists(filenameB))
{
// Remove the read-only attribute
FileAttributes attributes = File.GetAttributes(filenameB);
attributes &= ~FileAttributes.ReadOnly;
File.SetAttributes(filenameB, attributes);
// You can't OR the Normal attribute with other attributes--see MSDN.
File.SetAttributes(filenameB, FileAttributes.Normal);
}
To be fair, the documentation on the SetAttributes method isn't real clear about how to go about setting file attributes once a file is marked as Readonly. Sure, there's an example (using the Hidden attribute), but they don't explicitly say that you need to use an inverted bitmask to remove the Hidden or Readonly attributes. One could easily assume it's just how they chose to "unset" the attribute. It's also not clear from the documentation about what would happen, for instance, if you marked the file thusly:
File.SetAttributes(pathToFile, FileAttributes.Normal);
File.SetAttributes(pathToFile, FileAttributes.Archived);
Does this result in the file first having Normal attributes set, then only Archived, or does it result in the file having Normal set, and then _additionallyhavingArchived` set, resulting in a Normal, but Archived file? I believe it's the former, rather than the latter, based on how attributes are "removed" from a file using the inverted bitmask.
If anyone finds anything contrary, please post a comment and I'll update my answer accordingly.
HTH.
This may cause because user don't have sufficient permission to access file system ,
work around :
1,Try to run application in administrative mode
OR
2,Try to run visual studio in administrative mode (if you are using debugger)

File Path as Command Line Argument

This is very common thing but i am very confused to get around this.
Taking file path as command line argument in c#.
If i give input "F:\\" then this works perfect.
But when i give input "F:\" it gives output like F:".
I know this is because of backslash escape character.
But my problem is how to get around this without modifying user input because logically user input is correct.
Is it possible without modifying user input get correct path in this situation?
I also know that there is # character which can be used.
But as i said this is command line argument so the string is already in variable.
I also read some blogs but still i remain unable to resolve my problem.
C# Command-Line Parsing of Quoted Paths and Avoiding Escape Characters
EDIT :Actually my program is to list all the files inside directory so i am first checking for Directory.Exists(command line arguments) and then getting list of all the files if directory exist.
Ok so in that case when user gives Command line argument as i shown above logically the drive exist but just because of escape character it returns false.
Just think about printing the command line argument as follow.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("{0}", args[0]);
Console.Read();
}
}
I am having very less knowledge of c# thanks for helping.
Im not sure why your having a problem here. In M$ Windows, a directory can be specified with or without a back-slash so all of these are correct: c: and c:\ and c:\media and c:\media\. This is the same for Directory.Exists(path) and other functions like Directory.GetFiles(path).
Ths following is a very simple app to list directory files and in my environment it works regardless of whether I put a slash on the end. So c:\media\ gives me all my media files.
class Program
{
static void Main(string[] args)
{
string path = args[0];
Console.WriteLine("trying path: " + path);
if (Directory.Exists(path))
Directory.GetFiles(path).ToList().ForEach(s => Console.WriteLine(s));
else
Console.WriteLine("path not found");
}
}
One thing to note is that in visual studio, when using the debugger such as Quick Watch, it will show the escape character with backslashs. So if user enters c:\media\ the string will be stored as c:\media\ but when you quick watch the path in VS you'll see c:\\media\\; look deeper with the Text Visualisation feature and you'll see the path correctly shown as c:\media\.
You should use Path class and specifically Path.GetFullPath method to get correct full path.
class Program
{
static void Main(string[] args)
{
string path = Path.GetFullPath(args[0]);
Console.WriteLine("trying path: " + path);
if (Directory.Exists(path)){
var files = Directory.GetFiles(path);
foreach (var file in files) Console.WriteLine(file);
}
else
Console.WriteLine("path doesn't exist");
}
}
UPD. Paths with spaces should be passed in quotes. Or you should concat all your command line arguments, if path is the only input.
Use Environment.GetCommandLineArgs(). It will clean up the path.
See this link for more info: http://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs(v=vs.110).aspx
Well, if I understand correctly. You can use string.Format . There are overload methods that could help you without modifying much user input.
Sample code:
string[] inputs = ...
string output = string.Format("F:\\{0}\\{1}", inputs[0], inputs[1]);
C# interprets \ as an escape character. So \" is interpreted as "
Possible way to fix it (if you are sure that there is no " inside arguments:
string a = args[0].Replace('"', '\\');
I think your over thinking this. Logically that isnt valid input. \ is an escape character on the command prompt just as it is in c# inside of a string. What you have entered ("F:\") is an invalid value and it IS on the user to correct. The user is saying at this point that they want the quote.
Note that when you pass the filename in parameters, you need to have the access rights in the directory where file is placed, otherwise some parts of your application might fail unexpectedly and it might took you much time to figure out what's wrong there.
var args1 = Environment.GetCommandLineArgs().Skip(1);
if (args1 != null && args1.Count() > 0)
{
//do stuff
}

Directory.Move(): Access to Path is Denied

I'm writing this Windows Form Application in Visual Studio 2010 using C#.
There is a Execute button on the form, the user will hit the button, the program will generate some files and are stored in the Output folder (which is created by the program using Directory.CreateDirectory())
I want to create an Archive folder to save the output files from previous runs.
In the beginning of each run, I try to move the existing Output folder to the Archive folder, then create a new Output folder. Below is the function I ran to move directory.
static void moveToArchive()
{
if (!Directory.Exists("Archive")) Directory.CreateDirectory("Archive");
string timestamp = DateTime.Now.ToString("yyyyMMddHHmms");
try
{
Directory.Move("Output", "Archive\\" + timestamp);
}
catch(Exception e)
{
Console.WriteLine("Can not move folder: " + e.Message);
}
}
The problem I ran into confuses me a lot...
There are some times that I can successfully move the Output folder to archive, but sometimes it fails.
The error message I got from catching the exception is Access to path 'Output' is denied.
I have checked that all the files in the Output folder are not in use. I don't understand how access is denied sometimes and not all the times.
Can someone explain to me and show me how to resolve the problem?
--Edit--
After HansPassant comment, I modified the function a little to get the current directory and use the full path. However, I'm still having the same issue.
The function now looks like this:
static void moveToArchive()
{
string currentDir = Environment.CurrentDirectory;
Console.WriteLine("Current Directory = " + currentDir);
if (!Directory.Exists(currentDir + "\\Archive")) Directory.CreateDirectory(currentDir + "\\Archive");
string timestamp = DateTime.Now.ToString("yyyyMMddHHmms");
try
{
Directory.Move(currentDir + "\\Output", currentDir + "\\Archive\\" + timestamp);
}
catch(Exception e)
{
Console.WriteLine("Can not move folder: " + e.Message);
}
}
I printed out the current directory and it is just as what I was expecting, and I'm still having trouble using full path. Access to path 'C:\Users\Me\Desktop\FormApp\Output' is denied.
--Edit--
Thank you everyone for answering and commenting.
I think some of you miss this part so I'm going stress it a bit more.
The Directory.Move() sometimes work and sometimes fails.
When the function succeed, there was no problem. Output folder is moved to Archive
When the function fails, the exception message I got was Access to path denied.
Thank you all for the replies and help. I have figured out what the issue was.
It is because there was a file that's not completely closed.
I was checking the files that were generated, and missed the files the program was reading from.
All files that were generated were closed completely. It was one file I used StreamReader to open but didn't close. I modified the code and am now not having problem, so I figure that's were the issue was.
Thanks for all the comments and answers, that definitely help me with thinking and figuring out the problem.
See http://windowsxp.mvps.org/processlock.htm
Sometimes, you try to move or delete a file or folder and receive access violation or file in use - errors. To successfully delete a file, you will need to identify the process which has locked the file. You need to exit the process first and then delete the particular file. To know which process has locked a file, you may use one of the methods discussed in this article.
Using Process Explorer - download from http://download.sysinternals.com/files/ProcessExplorer.zip
Process Explorer shows you information about which handles and DLLs processes have opened or loaded.
Download Process Explorer from Microsoft site and run the program.
Click the Find menu, and choose Find Handle or DLL...
Type the file name (name of the file which is locked by some process.)
After typing the search phrase, click the Search button
You should see the list of applications which are accessing the file.
I bumped on the same problem recently. Using PE I'd figured that only process using that particular directory was explorer.exe. I'd opened few windows with explorer, one pointing to parent directory of one that I was about to move.
It appeared, that after I visited that sub-folder and then returned (even to root level!) the handle was still being kept by explorer, so C# was not able to modify it in any way (changing flags, attributes etc.).
I had to kill that explorer window in order to made C# operate properly.
File.SetAttributes(Application.dataPath + "/script", FileAttributes.Normal);
Directory.Move(Application.dataPath + "/script", Application.dataPath + "/../script");
This fixed my problem.
Try this:
If this does not solve, maybe check/change the antivirus, or the some other program is locking some file in or the folder.
static object moveLocker = new object();
static void moveToArchive()
{
lock (moveLocker)
{
System.Threading.Thread.Sleep(2000); // Give sometime to ensure all file are closed.
//Environment.CurrentDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
string applicationPath = System.AppDomain.CurrentDomain.BaseDirectory;
string archiveBaseDirectoryPath = System.IO.Path.Combine(applicationPath, "Archive");
if (!Directory.Exists(archiveBaseDirectoryPath)) Directory.CreateDirectory(archiveBaseDirectoryPath);
String timestamp = DateTime.Now.ToString("yyyyMMddHHmms");
String outputDirectory = System.IO.Path.Combine(Environment.CurrentDirectory, "Output");
String destinationTS = System.IO.Path.Combine(archiveBaseDirectoryPath, timestamp);
try
{
Directory.Move(outputDirectory, destinationTS);
}
catch (Exception ex)
{
Console.WriteLine("Can not move folder " + outputDirectory + " to: " + destinationTS + "\n" + ex.Message);
}
}
}
I had the same problem, it failed sometimes but not all the time. I thought I'd wrap it in a Try Catch block and present the user with an Access Denied message and once I wrapped it in the Try Catch block it stopped failing. I can't explain why.
If existingFile.FileName <> newFileName Then
Dim dir As New IO.DirectoryInfo(existingFile.FilePath)
Dim path As String = System.IO.Path.GetDirectoryName(dir.FullName)
newFileName = path & "\" & newFileName
File.SetAttributes(existingFile.FilePath, FileAttributes.Normal)
Try
IO.File.Move(existingFile.FilePath, newFileName)
Catch ex As Exception
End Try
End If
I had a similar problem. Renamed many directories in a loop when following the certain template. From time to time the program crashed on different directories. It helped to add a sleep thread before Directory.Move. I need to create some delay.
But it slows down the copying process.
foreach (var currentFullDirPath in Directory.GetDirectories(startTargetFullDirectory, "*", SearchOption.AllDirectories))
{
var shortCurrentFolderName = new DirectoryInfo(currentFullDirPath).Name.ToLower();
if (shortCurrentFolderName.Contains(shortSourceDirectoryName))
{
// Add Thread.Sleep(1000);
Thread.Sleep(1000);
var newFullDirName = ...;
Directory.Move(currentFullDirPath, newFullDirName);
}
}

getting file name and moving it

string fName = Path.GetFileName(tempPaths[z]);
if (!File.Exists(subAch + fName))
{
File.Move(tempPaths[z], subAch + fName);
Console.WriteLine("moved!!! from " + tempPaths[z] + " tooooo ");
}
tempPaths is a list with all the image file paths. e.g. ./images/image4.jpg
subAch is a directory string.
I wish to get the file name of the file then move them to another directory. But with the code above i kept getting error: file is being used by other process.
Is there anyway which get the file name and move them? I have tried fileStream but was confused by it.
Please advice.
Thank you!
Your code should work just fine. You just need to figure out who is locking the files.
I'd put the code inside the if-block in a try-catch block to deal with the locked files.
I will also recommend you to use Path.Combine instead of dir + file.
One thing: you are checking if subAch + tempPaths[z] exists, yet you are copying to a different location; subAch + fName.
File is being used by another process means exactly that. Someone/something is already using the file, so can't move it. You can always catch the error and moving everything else?
I have use a non-ideal way to grab the file name and move the files to another place.
tempPaths.AddRange(Directory.GetFiles(rawStorePath, filter, SearchOption.AllDirectories));
The code above gets all the directories of all the files in the folder set. The outcome with be something like this. tempPaths is a List.
"./images/glass_numbers_5.jpg"
"./images/G.JPG"
"./images/E.JPG"
"./images/F.JPG"
"./images/glass_numbers_0.jpg"
"./images/C.JPG"
"./images/B.JPG"
"./images/A.JPG"
"./images/D.JPG"
"./images/glass_numbers_7.jpg"
then after i use a loop to grab the file names.
for (int i = 0; i < tempPaths.Count; i++)
{
//Getting the original names of the images
int pLength = rawStorePath.Length;
string something = tempPaths[i].Remove(0, pLength);
if (!_tfileName.ContainsKey(tempPaths[i]))
{ _tfileName.Add(tempPaths[i], something); }
}
rawStorePath is the path of the targeted path e.g.: ./images/
tempPath[i] e.g. : ./images/G.JPG
So with the length i remove the letters and get the file name back.
Please advice me for a ideal way to do this if there is any.
Thanks!

Randomly Thrown IO Exceptions in C#

I have been working on a program to archive old client data for the company I work for. The program copies the data from the work server to the local machine, creates a .zip file of all the data, then copies it to the archive server.
After it does all that, it deletes the original files and the local copies. Every now and then, the program errors because it can't delete the local copies off my computer. It does not error every different folder that it zips. I will error after doing 300 of them, or after 5. It throws one of the 3 following errors,"The directory is not empty", "File is being used by another process", or "Access to the file is denied". I have tried setting the file attributes to normal, using a forced garbage collection, and ending the winzip process manually.
I really do not understand why it does this only sometimes. I am the admin on my computer and it should be able to delete the files. I figured something else has to be using it, but there should be nothing else using it on my machine except the program in Visual Studio. Thanks.
Below is the cleanup method where it is not deleting the files and the method that zips the files.
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void CleanUp(SqlConnection Connection, string jNumber, DirectoryInfo dir, bool error, string prefix)
{
if (!error | (!error & emptyFolder))
{
try
{
SqlCommand updateJob = new SqlCommand(string.Format("update job set archived = 1 where job = {0}", jNumber), sdiConnection);
updateJob.ExecuteNonQuery();
}
catch
{
WriteToLog("SQL Error: " + jNumber, "There was an error changing the archive bit to 1 after the job has been archived");
}
try
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch
{
WriteToLog("Error cleaning up after processing job", "There was an error garbage collecting.");
}
try
{
//path of the temporary folder created by the program
string tempDir = Path.Combine(Path.Combine(System.Environment.CurrentDirectory, "Temp"), jNumber);
//path of the destination folder
string destDir = Path.Combine(dir.ToString(), jNumber);
//SetFileAttributes(tempDir);
try
{
File.Delete(tempDir + ".zip");
}
catch (System.IO.IOException)
{
File.Delete(tempDir + ".zip");
}
try
{
Directory.Delete(destDir, true);
}
catch (System.IO.IOException)
{
Directory.Delete(destDir, true);
}
try
{
Directory.Delete(tempDir, true);
}
catch (System.IO.IOException)
{
Directory.Delete(tempDir, true);
}
}
catch
{
WriteToLog("File Error: " + jNumber, "There was an error removing files and/or folders after the job has been archived. Please check the source server and destination server to make sure everything copied correctly. The archive bit for this job was set.");
Directory.Delete(Path.Combine(System.Environment.CurrentDirectory, "Temp"), true);
Directory.CreateDirectory(Path.Combine(System.Environment.CurrentDirectory, "Temp"));
}
}
static bool ZipJobFolder(string jNumber, string jPath)
{
try
{
string CommandStr = #"L:\ZipFiles\winzip32.exe";
string parameters = "-min -a -r \"" + jNumber + "\" \"" + jPath + "\"";
ProcessStartInfo starter = new ProcessStartInfo(CommandStr, parameters);
starter.CreateNoWindow = true;
starter.RedirectStandardOutput = false;
starter.UseShellExecute = false;
Process process = new Process();
process.StartInfo = starter;
Console.WriteLine("Creating .zip file");
process.Start();
process.WaitForExit();
Process[] processes;
string procName = "winzip32.exe";
processes = Process.GetProcessesByName(procName);
foreach (Process proc in processes)
{
Console.WriteLine("Closing WinZip Process...");
proc.Kill();
}
}
catch
{
WriteToLog(jNumber, "There was error zipping the files of this job");
return false;
}
return true;
}
I have noticed this behavior using windows explorer, while deleting large folders with a lot of files and sub-folders. But after waiting a bit and then deleting again, it appears to work fine.
Because of that, I have always assumed it was a flaky behavior of the operating system.
Although this is not a solution, you could try it by making your application sleep for a small amount of time before attempting to delete those files, and see if the error occurs still.
If the errors go away it would appear to be related to some timing issue. I would myself want to know the source of the issue though.
Commenters are pointing to Anti Virus program. That would make sense, if that is true then you need to write some code to check if the file is locked before trying to delete. If it is locked then sleep for a bit, then check again until it is no longer locked and you can go ahead and delete it.
You just need to be careful not to get into an infinite race condition.
Edit:
There is a related question about How to best wait for a filelock to release check it out for ideas.
Edit2:
Here is another possible solution Wait until file is unlocked in .Net
Most likely you are getting a sharing violation - the delete can't get the exclusive file handle. One way this happens is the AV software gets triggered and doesn't finish scanning before the call to delete. It could also be that the WinZip process isn't fully dead yet.
Several ways to handle it:
1) On failure, sleep for a few seconds & try again.
2) I would probably not use WinZip & instead use ZipStorer (http://zipstorer.codeplex.com/). It will zip the file in the process and you won't have to do the kill step & you will have much more granular control. You could also do the zips in parallel by spinning up multiple threads.
One thing I found that helps is to not try to create temp files and directories in a single File.Move or File.Copy call. Rather, manually create the parent directories, starting at the highest level and working downwards. Finally, when all parent directories exist, Move or Copy the file.
Antivirus software could be an issue because if antivirus software is currently reading your file it will cause that, to be honest I've seen this pop up many a time when using the .NET framework and I just toss the handling in a loop and attempt to do whatever file operation is needed until it no longer throws the exception. This also happens if a file is currently being copied or is being registered in the buffer of the kernel if some kind of watcher is implemented.

Categories

Resources