I have the following code and my code does not catch the exception.
In my code I am trying to read all the files for which the access is granted.
var pathsToSearch = new Queue<string>();
var foundFiles = new List<string>();
pathsToSearch.Enqueue(startFolder);
while (pathsToSearch.Count > 0) {
var dir = pathsToSearch.Dequeue();
try {
var files = Directory.GetFiles(dir);
foreach (var file in Directory.GetFiles(dir)) {
foundFiles.Add(file);
}
foreach (var subDir in Directory.GetDirectories(dir)) {
pathsToSearch.Enqueue(subDir);
}
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e);
}
}
Why does the try catch not work properly or is there some mistake in my code ?
It sounds like you're running your program from Visual Studio, which catches First Chance Exceptions by default. You can turn off this option in Visual Studio. I believe this is under Debug > Exceptions, but you may also be able to disable this from the popup dialog that displays the exception.
Here's a Microsoft article that might be helpful: Understanding Exceptions while debugging with Visual Studio
Related
One example is this code:
try
{
string domain = o.SelectToken("response[" + i + "].domain").ToString();
...
}
catch(Exception)
{
continue;
}
Instead of just going on in the loop("continue"), vs halts and points at string domain = o.SelectToken("response[" + i + "].domain").ToString(); for an System.IndexOutOfRangeException.
Why is that?
You probably have 'break on all exceptions' selected in the Debug>Windows>Exception settings:
https://learn.microsoft.com/en-us/visualstudio/debugger/managing-exceptions-with-the-debugger?view=vs-2019
Unselecting this will let VS proceed.
You can do it by using two ways.
As suggested in MSDN, is to set it up in your Visual Studio (I believe it's 2019)
Debug > Windows > Exception Settings: Search for index and untick.
Please add exception to handle exception in your code..
catch(IndexOutOfRangeException e)
{
// handle it like logging it in file and continue
continue;
}
catch(Exception)
{
continue;
}
I am trying to program a Windows service that automatically deletes the file from a specific folder. But I encountered an error:
Cannot access the file. The file is currently in use by another process/program.
I tried to do the following, but still get the same error.
string[] files = Directory.GetFiles(#"C:\Users\ASIM\AppData\Local\Temp");
// string[] directories = Directory.GetDirectories(#"C:\Users\ASIM\AppData\Local\Temp", "p*", SearchOption.TopDirectoryOnly);
if (files != null || files.Length != 0)
{
{
foreach (string f in files)
{
try
{
File.Delete(f);
}
finally { }
}
}
}
so how to skip deleting a file if it is in use?
There is no point checking if the file is deletable before deleting it because there will be a small window of opportunity between your check and the delete, where another process will open the file. The best idea is to try and delete it and handle the exception if it occurrs.
Your try/finally should be try/catch with the appropriate exception:
try
{
File.Delete(f);
}
catch(IOException ex)
{
// Probably some logging here
}
i am running in an exception when I want to update extensions in Visual Studio 2015. Each and every time I am updating an extension I will get an file is already in use exception. I tracked this down to the file *.pkgdef.
I am running in this exception on my working pc only. This machine runs Windows 8.1 with McAfee Antivirus, Firewall and Drive Encryption. I have the feeling that drive encryption has something to do with this exception but I can not say this for sure.
I debugged VSIXInstaller and found something that I believe is a bug.
The class is ExtensionManagerService.cs in the assembly Microsoft.VisualStudio.ExtensionManager.Implementation.dll .
private void AtomicallyDeleteFiles(IEnumerable<string> filePaths, bool justMarkForDeletion)
{
foreach (FileStream fileStream in this.LockFiles(filePaths, (IList<string>) null))
{
if (justMarkForDeletion)
{
string str = fileStream.Name + ".deleteme";
File.Delete(str);
File.Move(fileStream.Name, str);
}
else
File.Delete(fileStream.Name);
fileStream.Close();
}
}
The LockFiles method is implemented as followed:
private IEnumerable<FileStream> LockFiles(IEnumerable<string> filePaths, IList<string> inUse = null)
{
List<FileStream> list = new List<FileStream>();
foreach (string path in filePaths)
{
try
{
FileAttributes attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
FileAttributes fileAttributes = attributes & ~FileAttributes.ReadOnly;
File.SetAttributes(path, fileAttributes);
}
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.Delete);
list.Add(fileStream);
}
catch (Exception ex)
{
if (ex is FileNotFoundException)
{
try
{
Registry.SetValue("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\VisualStudio\\Extensibility\\ExtensionSDKDeletionListStore\\", "ScanForDeleteMeExtensionSDKsAtStartup", (object) 1, RegistryValueKind.DWord);
Registry.SetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\Extensibility\\ExtensionSDKDeletionListStore\\", "ScanForDeleteMeExtensionSDKsAtStartup", (object) 1, RegistryValueKind.DWord);
}
catch
{
}
}
if (inUse == null)
{
foreach (Stream stream in list)
stream.Close();
throw;
}
else
inUse.Add(path);
}
}
return (IEnumerable<FileStream>) list;
}
The exception happens at File.Move in AtomicallyDeleteFiles. I think that at that point a File.Copy was intended to be used. The file can not be moved because it was locked in the first place.
What I could not determine is why this only happens on my McAfee machine. But this problem was reported also here Can't Update or Uninstall NuGet Package Manager in VS2012 and here http://www.paraesthesia.com/archive/2013/07/30/upgrading-nuget-the-process-cannot-access-the-file-because-it.aspx/.
I do not know how can I get in touch with the Visual Studio Team. Would you consider this a bug too ? Can anyone help me reporting this ?
Regards
T4E
I think that the proper place to put feedback to Visual Studio is Microsoft Connect. It's unfortunate that VS is not open source so you can't offer them pull request. I suffer from the same issue and your finding seems reasonable -- although the fact that I too have McAfee on my machine is suspicious.
I use Assembly.LoadFile(string path) to load assembly to C# program. It works perfectly on my PC and two notebooks but... when I tried to send this app to my friend it crashed just after this call without any exceptions. We use same versions of .NET Framework, everything must be fine. I cant understand what happens. No exceptions, no errors, just "silent" return.
I also tried to use LoadFrom but nothing changed.
I use absolute path for dll files
public LoadedType[] LoadFrom(string path)
{
Assembly assembly = Assembly.LoadFile(path);
}
and calling method is
Loader loader = new Loader();
string[] paths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll", SearchOption.TopDirectoryOnly);
List<string> corrupted = new List<string>();
foreach (string path in paths)
{
try
{
LoadedType[] loadedTypes = loader.LoadFrom(path);
MessageBox.Show("loaded");
if (loadedTypes.Length == 0)
{
continue;
}
foreach (LoadedType loadedT in loadedTypes)
{
AvailableTypes.Add(loadedT);
}
}
catch (ReflectionTypeLoadException)
{
corrupted.Add(Path.GetFileName(path));
}
}
MessageBox does not appear.
Could somebody explain me whats wrong and why this code works on three PCs and does not work on another two PCs with the same Framework version?
using the code above you can not know if is there an exception or not, because you catch just exception of type ReflectionTypeLoadException, add another catch(Exception ex).
Check that string[] paths is not empty.
check that these assemblies are not used by another process.
check that you have access to read these assemblies.
You have to consider other types of possible exceptions as well:
try
{
// Ignore assemblies we can't load. They could be native, etc...
Assembly.LoadFrom(assemblyFile);
}
catch (Win32Exception) { }
catch (ArgumentException) { }
catch (FileNotFoundException) { }
catch (PathTooLongException) { }
catch (BadImageFormatException) { }
catch (SecurityException) { }
In my network, there are some files whose access is simply blocked.
A user cannot open nor read the file.
When I try to open the file, the only message that I get is "Access Denied".
bool isReadOnly = ((File.GetAttributes(Path) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);
I tried other options available under FileAttributes class. Nothing is matched for "Access Denied".
In short, how do I know whether a file is access-denied to me or not in c#. I am using WPF and visual studio .net 2010
Whenever I try to access it through code, I simply get an exception. When I try to open it manually I get something like "Access Denied."
try
{
IEs = from file in Directory.EnumerateFiles(sDirectoryToBeSearched, sValidExtensions, SearchOption.AllDirectories)
from str in File.ReadLines(file)
where (str.IndexOf(sSearchItem, StringComparison.OrdinalIgnoreCase) >= 0)
select file;
}
catch
{
MessageBox ("Exception arised");
}
Even If used try catch, exception is not handled because of LINQ query. Any solutions ?>
Instead of using LINQ try using recursion, that way if a file or folder access is denied the rest of procedure will continue. Example bellow.
private void SearchDirectory(string folder)
{
foreach (string file in Directory.GetFiles(folder))
{
try
{
// do work;
}
catch
{
// access to the file has been denied
}
}
foreach (string subDir in Directory.GetDirectories(folder))
{
try
{
SearchDirectory(subDir);
}
catch
{
// access to the folder has been denied
}
}
}
You don't have to check the FileAttributes, you need to check the security lists.
You can look at the example here to see how to work with the FileSecurity class.