System.IO.File.Delete throws Arithmetic operation resulted in an overflow - c#

I have this weird error. When I call System.IO.File.Delete(), it throws
JobCleaner.CleanFiles(): Unable to delete file: D:\WorkerData\4\Run128\Run_TEMPLATE_Rail_Scenario_Type35_INFHD2_NO_TAX_NOMEP\out‌​put_panels\FileIndex55.bin
Error: Arithmetic operation resulted in an overflow.
There is no stack trace.
Here is my code:
foreach (string strFile in System.IO.Directory.GetFiles(strFolder))
{
try { System.IO.File.Delete(strFile); }
catch (Exception ex)
{
//Exception here
AddToLog("JobCleaner.CleanFiles(): Error occurred when trying to delete file \"" + strFile + "\".\nError:\n" + ex.Message);
return false;
}
}
Any idea? I tried everything, I check the security on the folder. I enabled "Everyone" with full controls, but still encounter this "Arithmetic operation resulted in an overflow" exception.
Can anyone help, please? I am using Windows 2012 R2 Datacenter to run my application.

I wouldn't expect it to throw an arithmetic exception, but I have observed some weird behavior when you modify an IEnumerable within the foreach that is walking it. Try moving the file listing out of the loop, like this:
string[] files = System.IO.Directory.GetFiles(strFolder);
foreach (string strFile in files)
{
try { System.IO.File.Delete(strFile); }
catch (Exception ex)
{
//Exception here
AddToLog("JobCleaner.CleanFiles(): Error occurred when trying to delete file \"" + strFile + "\".\nError:\n" + ex.Message);
return false;
}
}

Related

Exclude System Hardlinks from File.Copy

So my problem is that I want to export my user account.
But inside C:\%user%\AppData\Local\ are System Hardlinks e.g.: Application Data which I obviously have no right to use them.
Is there a way to exclude those System Hardlinks from the copying process?
I'm not sure what you mean with hard links, but this might help you
foreach (var dir in new DirectoryInfo(#"c:\users\xxxxxx\AppData\Local").GetDirectories())
{
if (dir.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
Console.WriteLine(dir.Name + " is symbolic, skip it");
}
else
{
//do your copy here
}
}
So I fixed the issue with Exception handling, doing it this way:
FileInfo[] sourceFiles = null;
try {
sourceFiles = new DirectoryInfo(sourcePath).GetFiles();
} catch (Exception ex) {
WriteLog(LogPath, ex + "");
return;
}
Since I'm a bit new to exception handling, I couldn't work it out for the first few hours on this problem.

Deleting Files with c#

I´m making a program to delete some files that I have on my PC. But when I try to do it, I get some error messages like this:
If you are attempting to access a file, make sure it is not ReadOnly.
Make Sure you have sufficient privileges to access this resource.
Get general Help for this exception.
foreach (string subFich in SubFicheiros)
{
listBox.Items.Add("- Deleting File: " + subFich.Substring(Pasta.Length + 1, subFich.Length - Pasta.Length - 1));
ficheirosEncontrador++;
}
try
{
Directory.Delete(Pasta, true);
}
catch (IOException)
{
Thread.Sleep(0);
//The Message Error appears here on this code right below:
Directory.Delete(Pasta, true);
}
catch (UnauthorizedAccessException)
{
Directory.Delete(Pasta, true);
}
}
I would like to get some help with this.
How do i ask the user, to let me get the privilegies to delete it.
Well.. what your code doing is: You're deleting the directory and if it gives any exception then you're again trying to do the same step where you got exception.
First of all error is because files are set to read only or because you dont have enough rights to delete the directory (or probably some process is using the files which you are trying to delete)
foreach (string subFich in SubFicheiros)
{
listBox.Items.Add("- Deleting File: " + subFich.Substring(Pasta.Length + 1, subFich.Length - Pasta.Length - 1));
ficheirosEncontrador++;
}
try
{
var di = new DirectoryInfo(Pasta);
di.Attributes &= ~FileAttributes.ReadOnly;
Directory.Delete(Pasta, true);
}
catch (Exception EE)
{
MessageBox.Show("Error: "+ EE.toString());
}
if this code still doesn't work check if you have admin rights to delete that folder
Sounds like your file is read-only, or you do not have the right to remove the file you want based on your user login.

trying to delete a file, doesnt delete or throw error

At the end of the month I copy a file over to a different location and remove the original:
System.IO.File.Copy(fileLocation + PLU.FolderPath, destinationFilePath, true);
System.IO.File.Delete(PLU.FolderPath);
The file copies but it doesnt remove, it doesnt remove because the file doesnt exist.
PLU.FolderPath holds: PLU_104.DAT, which is why I need to use the 'fileLocation + PLU.FolderPath' in the copy.
Shouldnt it throw an error if it doesnt delete though? Even if the file it is looking for is not there?
I've tried it inside a try catch but it still doesnt throw an error:
System.IO.File.Copy(fileLocation + PLU.FolderPath, destinationFilePath, true);
try
{
System.IO.File.Delete(PLU.FolderPath);
}
catch (Exception e)
{
Log.Quiet("Didnt delete" + e.Message);
}
From Msdn
If the file to be deleted does not exist, no exception is thrown.
http://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx

JPEG Viewer can't be called from Process.start

Here is my code
if (row.Cells[5].Value.ToString().ToUpper() == "JPG")
{
try
{
// string notepadPath = Path.Combine(Environment.SystemDirectory, "MSPAINT.exe");
string notepadPath = Path.Combine(Environment.SystemDirectory, "JPEGViewer.exe");
if (File.Exists(notepadPath))
Process.Start(notepadPath, location);
else
throw new Exception("Can't locate Notepad");
}
catch (Exception ee)
{
MessageBox.Show("Exception is " + ee.Message);
}
}
Even Though the String notepadPath contains the Folder and executable C:\Windows\system32\JPEGViewer.exe the line ** if (File.Exists(notepadPath)) doesn't find the exe even though it is there. If I attempt to bypass the Exist and perform the Process.Start(notepadPath, location); It throws an exception The system cannot find the file specified
**
Please note that this same code works perfectly when calling MSPAINT.EXE
Any ideas will be greatly appreciated,

Can not delete files from Recent folder

I am writing a Software that can delete Temporary files, Prefetch data, files in Recent folder and so on. My problem is I can delete files from Temp folder successfully, but when I try for Recent folder, an exception is thrown, "Access to path...is denied".
PS: According to some other questions, I have set File attributes to normal, but still no luck. Please help me on this issue. For your better understand, I put some code here:
public Boolean CleanRecentData()
{
isAllClean = true;
String SysRecentPath = System.Environment.GetEnvironmentVariable("USERPROFILE") + "\\Recent";
DirectoryInfo SysRecDir = new DirectoryInfo(SysRecentPath);
File.SetAttributes(SysRecentPath, FileAttributes.Normal);
foreach (FileInfo fi in SysRecDir.GetFiles()) //Access Denied
//Exception is thrown here
{
try
{
fi.Delete();
}
catch (Exception ex)
{
recentLogLines.AppendLine(ex.Message);
isAllClean = false;
}
}
foreach (DirectoryInfo dir in SysRecDir.GetDirectories())
{
try
{
dir.Delete(true);
}
catch (Exception ex)
{
recentLogLines.AppendLine(ex.Message);
isAllClean = false;
}
}
return isAllClean;
}
Are you able to access the Recent folder via Windows Explorer?
You could go ahead and change the permissions in your system, but NOT in your users systems.
Therefore you could handle this exception condition in two ways.
You need to check if you have file access before accessing, using FileIOPermission but this might be redundant and wasteful if you are doing it on too many files.
Just try to open the file and put your effort into a good exception handler if it fails
Reference

Categories