Getting all the assemblies in a package in Xamarin Android - c#

I would like to retrieve a list with all the Assemblies in an application package in order to load them dynamically.
I'm trying with this code:
public static IEnumerable<Assembly> AssembliesInAppFolder
{
get
{
var entryAssembly = Assembly.GetExecutingAssembly();
var path = entryAssembly.Location;
var folder = Path.GetDirectoryName(path);
var assemblies = new Collection<Assembly>();
var fileNames = FilterFiles(folder, ".dll", ".exe");
foreach (var fileName in fileNames)
{
try
{
assemblies.Add(Assembly.LoadFile(fileName));
}
catch (FileNotFoundException)
{
}
catch (FileLoadException)
{
}
catch (BadImageFormatException)
{
}
}
return assemblies;
}
}
public static IEnumerable<string> FilterFiles(string path, params string[] extensionsWithNoWildcard)
{
return
Directory
.EnumerateFiles(path, "*.*")
.Where(file => extensionsWithNoWildcard.Any(x => file.EndsWith(x, StringComparison.OrdinalIgnoreCase)));
}
But it doesn't work in Android (in Release mode, it throws at Directory.EnumerateFiles(path, "*.*") - where path is an empty string saying this:
"System.ArgumentException: The specified path is not of a legal form (empty)."

Related

C#: try foreach catch continue [duplicate]

I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method comes across a folder that it cannot access, it throws an exception and the process stops.
How do I ignore this exception (and ignore the protected folder/file) and continue adding accessible files to the list?
try
{
if (cbSubFolders.Checked == false)
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string fileName in files)
ProcessFile(fileName);
}
else
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
foreach (string fileName in files)
ProcessFile(fileName);
}
lblNumberOfFilesDisplay.Enabled = true;
}
catch (UnauthorizedAccessException) { }
finally {}
You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array):
using System;
using System.IO;
static class Program
{
static void Main()
{
string path = ""; // TODO
ApplyAllFiles(path, ProcessFile);
}
static void ProcessFile(string path) {/* ... */}
static void ApplyAllFiles(string folder, Action<string> fileAction)
{
foreach (string file in Directory.GetFiles(folder))
{
fileAction(file);
}
foreach (string subDir in Directory.GetDirectories(folder))
{
try
{
ApplyAllFiles(subDir, fileAction);
}
catch
{
// swallow, log, whatever
}
}
}
}
Since .NET Standard 2.1 (.NET Core 3+, .NET 5+), you can now just do:
var filePaths = Directory.EnumerateFiles(#"C:\my\files", "*.xml", new EnumerationOptions
{
IgnoreInaccessible = true,
RecurseSubdirectories = true
});
According to the MSDN docs about IgnoreInaccessible:
Gets or sets a value that indicates whether to skip files or directories when access is denied (for example, UnauthorizedAccessException or SecurityException). The default is true.
Default value is actually true, but I've kept it here just to show the property.
The same overload is available for DirectoryInfo as well.
This simple function works well and meets the questions requirements.
private List<string> GetFiles(string path, string pattern)
{
var files = new List<string>();
var directories = new string[] { };
try
{
files.AddRange(Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly));
directories = Directory.GetDirectories(path);
}
catch (UnauthorizedAccessException) { }
foreach (var directory in directories)
try
{
files.AddRange(GetFiles(directory, pattern));
}
catch (UnauthorizedAccessException) { }
return files;
}
A simple way to do this is by using a List for files and a Queue for directories.
It conserves memory.
If you use a recursive program to do the same task, that could throw OutOfMemory exception.
The output: files added in the List, are organised according to the top to bottom (breadth first) directory tree.
public static List<string> GetAllFilesFromFolder(string root, bool searchSubfolders) {
Queue<string> folders = new Queue<string>();
List<string> files = new List<string>();
folders.Enqueue(root);
while (folders.Count != 0) {
string currentFolder = folders.Dequeue();
try {
string[] filesInCurrent = System.IO.Directory.GetFiles(currentFolder, "*.*", System.IO.SearchOption.TopDirectoryOnly);
files.AddRange(filesInCurrent);
}
catch {
// Do Nothing
}
try {
if (searchSubfolders) {
string[] foldersInCurrent = System.IO.Directory.GetDirectories(currentFolder, "*.*", System.IO.SearchOption.TopDirectoryOnly);
foreach (string _current in foldersInCurrent) {
folders.Enqueue(_current);
}
}
}
catch {
// Do Nothing
}
}
return files;
}
Steps:
Enqueue the root in the queue
In a loop, Dequeue it, Add the files in that directory to the list, and Add the subfolders to the queue.
Repeat untill the queue is empty.
see https://stackoverflow.com/a/10728792/89584 for a solution that handles the UnauthorisedAccessException problem.
All the solutions above will miss files and/or directories if any calls to GetFiles() or GetDirectories() are on folders with a mix of permissions.
Here's a full-featured, .NET 2.0-compatible implementation.
You can even alter the yielded List of files to skip over directories in the FileSystemInfo version!
(Beware null values!)
public static IEnumerable<KeyValuePair<string, string[]>> GetFileSystemInfosRecursive(string dir, bool depth_first)
{
foreach (var item in GetFileSystemObjectsRecursive(new DirectoryInfo(dir), depth_first))
{
string[] result;
var children = item.Value;
if (children != null)
{
result = new string[children.Count];
for (int i = 0; i < result.Length; i++)
{ result[i] = children[i].Name; }
}
else { result = null; }
string fullname;
try { fullname = item.Key.FullName; }
catch (IOException) { fullname = null; }
catch (UnauthorizedAccessException) { fullname = null; }
yield return new KeyValuePair<string, string[]>(fullname, result);
}
}
public static IEnumerable<KeyValuePair<DirectoryInfo, List<FileSystemInfo>>> GetFileSystemInfosRecursive(DirectoryInfo dir, bool depth_first)
{
var stack = depth_first ? new Stack<DirectoryInfo>() : null;
var queue = depth_first ? null : new Queue<DirectoryInfo>();
if (depth_first) { stack.Push(dir); }
else { queue.Enqueue(dir); }
for (var list = new List<FileSystemInfo>(); (depth_first ? stack.Count : queue.Count) > 0; list.Clear())
{
dir = depth_first ? stack.Pop() : queue.Dequeue();
FileSystemInfo[] children;
try { children = dir.GetFileSystemInfos(); }
catch (UnauthorizedAccessException) { children = null; }
catch (IOException) { children = null; }
if (children != null) { list.AddRange(children); }
yield return new KeyValuePair<DirectoryInfo, List<FileSystemInfo>>(dir, children != null ? list : null);
if (depth_first) { list.Reverse(); }
foreach (var child in list)
{
var asdir = child as DirectoryInfo;
if (asdir != null)
{
if (depth_first) { stack.Push(asdir); }
else { queue.Enqueue(asdir); }
}
}
}
}
This should answer the question. I've ignored the issue of going through subdirectories, I'm assuming you have that figured out.
Of course, you don't need to have a seperate method for this, but you might find it a useful place to also verify the path is valid, and deal with the other exceptions that you could encounter when calling GetFiles().
Hope this helps.
private string[] GetFiles(string path)
{
string[] files = null;
try
{
files = Directory.GetFiles(path);
}
catch (UnauthorizedAccessException)
{
// might be nice to log this, or something ...
}
return files;
}
private void Processor(string path, bool recursive)
{
// leaving the recursive directory navigation out.
string[] files = this.GetFiles(path);
if (null != files)
{
foreach (string file in files)
{
this.Process(file);
}
}
else
{
// again, might want to do something when you can't access the path?
}
}
I prefer using c# framework functions, but the function i need will be included in .net framework 5.0, so i have to write it.
// search file in every subdirectory ignoring access errors
static List<string> list_files(string path)
{
List<string> files = new List<string>();
// add the files in the current directory
try
{
string[] entries = Directory.GetFiles(path);
foreach (string entry in entries)
files.Add(System.IO.Path.Combine(path,entry));
}
catch
{
// an exception in directory.getfiles is not recoverable: the directory is not accessible
}
// follow the subdirectories
try
{
string[] entries = Directory.GetDirectories(path);
foreach (string entry in entries)
{
string current_path = System.IO.Path.Combine(path, entry);
List<string> files_in_subdir = list_files(current_path);
foreach (string current_file in files_in_subdir)
files.Add(current_file);
}
}
catch
{
// an exception in directory.getdirectories is not recoverable: the directory is not accessible
}
return files;
}

Where should be stored a storage file

I have a Xamarin Forms application in which I want to read a txt file. In my android project the file is placed in the assets folder with these properties :
Build action : Android Asset
Copy options : Allways copy.
And I am capabale to read the file with this code :
public string GetAppSetting(string name)
{
string retVal = "";
try
{
using (StreamReader sr = new StreamReader(AndroidHelper.Assets.Open("AppSettings.txt")))
{
var result = sr.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in result)
{
if (line.StartsWith(name + ":"))
return line.Split(':')[1];
}
}
}
catch (Exception ex)
{
ParseError(ex, "GetConnectionString");
}
return retVal;
}
On the other hand, in the uwp project, I have allways the exception File Not Found!
I put the file in the root of the project and tried to put in the assets folder too. It doesn't change the result. File Not Found!
Build action : Content (Tried other options too).
Copy options : Allways copy.
Here is my code to read the file :
private async Task<string> ReadFileAsync(string name)
{
string retVal = "parameter not found";
try
{
Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("AppSettings.txt");
string str = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);
foreach (var line in str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
{
if (line.StartsWith(name + ":"))
return line.Split(':')[1];
}
}
catch (Exception ex)
{
MainHelper.ParseError(ex, "UWP readFileAsync");
}
return retVal;
}
What is wrong wiht my code ? Or where should I place the AppSettings.txt ?
For UWP,
I suggest you to set the file as an "Embedded Resource" (Build Action)
To ensure your file is loaded as an embedded resource at runtime, you can enumerate all your assembly's resources like this:
var resourceNames = anotherSameResAssemblyInstance.GetType()
.GetTypeInfo().Assembly
.GetManifestResourceNames();
Then, you can open the file as a stream like this:
string myFileResourceStream = "{YourAppNamespace}.AppSettings.txt";
var myFileResourceStream = someAssembly.GetManifestResourceStream(name);
Where 'YourAppNamespace' is the namespace in your app where is embedded the file. To get the correct full name, just check all values returned by GetManifestResourceNames() method.
Example:
var myFile = resourceNames.Where(x => x.Contains("AppSettings.txt")).FirstOrDefault();
if (myFile != null)
{
var str = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream(myFile);
}
It should now work.
In the UWP MainPage Xaml.cs change the LoadApplication:
namespace MyApp.UWP
{
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
LoadApplication(new MyApp.App(Windows.Storage.ApplicationData.Current.LocalFolder.Path));
}
}
}
Then in the app.Xaml.cs add:
public static string path;
public App(string paTh)
{
InitializeComponent();
path = paTh.ToString();
MainPage = new ContentPage();
}
Then use App.path as the Windows storage path.

Powershell iterate through list<string> returned from c# class library

I have a powershell script that calls a c# library (.net framework) and returns a list or IEnumerable, I have tried both.
$scriptPath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptPath
$dllPath = $dir + "\MyCacheTools.dll"
[Reflection.Assembly]::LoadFrom($dllPath)
$files = [MyCacheTools.CacheTools]::DirSearch($cachePath))
ForEach ($file in $files) {
Write-Output $file
}
C#
public class CacheTools
{
public static IEnumerable<string> DirSearch(string path)
{
var t = GetFiles(path);
return t;
}
static IEnumerable<string> GetFiles(string path)
{
Queue<string> queue = new Queue<string>();
queue.Enqueue(path);
while (queue.Count > 0)
{
path = queue.Dequeue();
try
{
foreach (string subDir in Directory.GetDirectories (path))
{
queue.Enqueue(subDir);
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
DirectoryInfo source = new DirectoryInfo(path);
FileInfo[] files = null;
try
{
files = source.GetFiles();
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
if (files != null)
{
for (int i = 0; i < files.Length; i++)
{
yield return files[i].Name;
}
}
}
}
}
I am having issues iterating through the list that is returned.
I would really appreciated a hand.
Windows 10, powershell 5.1
(edit)
The issue I was having was that it appeared nothing was being returned. $files displayed nothing. I was running it in the visual studio console and we seeing results. As it turns out, for my system, I had to run it in admin mode. I wasn't seeing the error in powershell ISE

Denied access to User Folder

I Need to find my pictures in my User folder. But I get the runtime error Access Denied
Here is my code
static void Main(string[] args)
{
string pic = "*.jpg";
string b = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string appdata = Path.Combine(b, "AppData"); // I Dont want search in this folder.
string data = Path.Combine(b, "Data aplikací"); // Here also not.
foreach (string d in Directory.GetDirectories(b))
{
try
{
if ((d == data) || (d == appdata))
{
continue;
}
else
{
foreach (string f in Directory.GetFiles(d, pic))
{
//...
}
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
}
Running the application as admin doesn't work either. How to avoid this?
check if the folder is read only (in windows) if it is, just clear the read only flag.
if it isn't read only, make sure that the admin user has full rights on that folder. You can check this by right clicking on the folder --> properties --> security
check out this link for more information on how to set it programatically:
C# - Set Directory Permissions for All Users in Windows 7
Oh, don't go changing your directory/folder permissions - that's just asking for future pain.
There's no "one-liner" solution here - basically, you need to recursively walk through the folder structure looking for the files you care about, and absorbing/eating the UnauthorizedAccessExceptions along the way (you could avoid the exception altogether by checking DirectoryInfo.GetAccessControl, but that's a whole different question)
Here's a blob o'code:
void Main()
{
var profilePath = Environment
.GetFolderPath(Environment.SpecialFolder.UserProfile);
var imagePattern = "*.jpg";
var dontLookHere = new[]
{
"AppData", "SomeOtherFolder"
};
var results = new List<string>();
var searchStack = new Stack<string>();
searchStack.Push(profilePath);
while(searchStack.Count > 0)
{
var path = searchStack.Pop();
var folderName = new DirectoryInfo(path).Name;
if(dontLookHere.Any(verboten => folderName == verboten))
{
continue;
}
Console.WriteLine("Scanning path {0}", path);
try
{
var images = Directory.EnumerateFiles(
path,
imagePattern,
SearchOption.TopDirectoryOnly);
foreach(var image in images)
{
Console.WriteLine("Found an image! {0}", image);
results.Add(image);
}
var subpaths = Directory.EnumerateDirectories(
path,
"*.*",
SearchOption.TopDirectoryOnly);
foreach (var subpath in subpaths)
{
searchStack.Push(subpath);
}
}
catch(UnauthorizedAccessException nope)
{
Console.WriteLine("Can't access path: {0}", path);
}
}
}

Error preventing any data from being written to array? [duplicate]

I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method comes across a folder that it cannot access, it throws an exception and the process stops.
How do I ignore this exception (and ignore the protected folder/file) and continue adding accessible files to the list?
try
{
if (cbSubFolders.Checked == false)
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string fileName in files)
ProcessFile(fileName);
}
else
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
foreach (string fileName in files)
ProcessFile(fileName);
}
lblNumberOfFilesDisplay.Enabled = true;
}
catch (UnauthorizedAccessException) { }
finally {}
You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array):
using System;
using System.IO;
static class Program
{
static void Main()
{
string path = ""; // TODO
ApplyAllFiles(path, ProcessFile);
}
static void ProcessFile(string path) {/* ... */}
static void ApplyAllFiles(string folder, Action<string> fileAction)
{
foreach (string file in Directory.GetFiles(folder))
{
fileAction(file);
}
foreach (string subDir in Directory.GetDirectories(folder))
{
try
{
ApplyAllFiles(subDir, fileAction);
}
catch
{
// swallow, log, whatever
}
}
}
}
Since .NET Standard 2.1 (.NET Core 3+, .NET 5+), you can now just do:
var filePaths = Directory.EnumerateFiles(#"C:\my\files", "*.xml", new EnumerationOptions
{
IgnoreInaccessible = true,
RecurseSubdirectories = true
});
According to the MSDN docs about IgnoreInaccessible:
Gets or sets a value that indicates whether to skip files or directories when access is denied (for example, UnauthorizedAccessException or SecurityException). The default is true.
Default value is actually true, but I've kept it here just to show the property.
The same overload is available for DirectoryInfo as well.
This simple function works well and meets the questions requirements.
private List<string> GetFiles(string path, string pattern)
{
var files = new List<string>();
var directories = new string[] { };
try
{
files.AddRange(Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly));
directories = Directory.GetDirectories(path);
}
catch (UnauthorizedAccessException) { }
foreach (var directory in directories)
try
{
files.AddRange(GetFiles(directory, pattern));
}
catch (UnauthorizedAccessException) { }
return files;
}
A simple way to do this is by using a List for files and a Queue for directories.
It conserves memory.
If you use a recursive program to do the same task, that could throw OutOfMemory exception.
The output: files added in the List, are organised according to the top to bottom (breadth first) directory tree.
public static List<string> GetAllFilesFromFolder(string root, bool searchSubfolders) {
Queue<string> folders = new Queue<string>();
List<string> files = new List<string>();
folders.Enqueue(root);
while (folders.Count != 0) {
string currentFolder = folders.Dequeue();
try {
string[] filesInCurrent = System.IO.Directory.GetFiles(currentFolder, "*.*", System.IO.SearchOption.TopDirectoryOnly);
files.AddRange(filesInCurrent);
}
catch {
// Do Nothing
}
try {
if (searchSubfolders) {
string[] foldersInCurrent = System.IO.Directory.GetDirectories(currentFolder, "*.*", System.IO.SearchOption.TopDirectoryOnly);
foreach (string _current in foldersInCurrent) {
folders.Enqueue(_current);
}
}
}
catch {
// Do Nothing
}
}
return files;
}
Steps:
Enqueue the root in the queue
In a loop, Dequeue it, Add the files in that directory to the list, and Add the subfolders to the queue.
Repeat untill the queue is empty.
see https://stackoverflow.com/a/10728792/89584 for a solution that handles the UnauthorisedAccessException problem.
All the solutions above will miss files and/or directories if any calls to GetFiles() or GetDirectories() are on folders with a mix of permissions.
Here's a full-featured, .NET 2.0-compatible implementation.
You can even alter the yielded List of files to skip over directories in the FileSystemInfo version!
(Beware null values!)
public static IEnumerable<KeyValuePair<string, string[]>> GetFileSystemInfosRecursive(string dir, bool depth_first)
{
foreach (var item in GetFileSystemObjectsRecursive(new DirectoryInfo(dir), depth_first))
{
string[] result;
var children = item.Value;
if (children != null)
{
result = new string[children.Count];
for (int i = 0; i < result.Length; i++)
{ result[i] = children[i].Name; }
}
else { result = null; }
string fullname;
try { fullname = item.Key.FullName; }
catch (IOException) { fullname = null; }
catch (UnauthorizedAccessException) { fullname = null; }
yield return new KeyValuePair<string, string[]>(fullname, result);
}
}
public static IEnumerable<KeyValuePair<DirectoryInfo, List<FileSystemInfo>>> GetFileSystemInfosRecursive(DirectoryInfo dir, bool depth_first)
{
var stack = depth_first ? new Stack<DirectoryInfo>() : null;
var queue = depth_first ? null : new Queue<DirectoryInfo>();
if (depth_first) { stack.Push(dir); }
else { queue.Enqueue(dir); }
for (var list = new List<FileSystemInfo>(); (depth_first ? stack.Count : queue.Count) > 0; list.Clear())
{
dir = depth_first ? stack.Pop() : queue.Dequeue();
FileSystemInfo[] children;
try { children = dir.GetFileSystemInfos(); }
catch (UnauthorizedAccessException) { children = null; }
catch (IOException) { children = null; }
if (children != null) { list.AddRange(children); }
yield return new KeyValuePair<DirectoryInfo, List<FileSystemInfo>>(dir, children != null ? list : null);
if (depth_first) { list.Reverse(); }
foreach (var child in list)
{
var asdir = child as DirectoryInfo;
if (asdir != null)
{
if (depth_first) { stack.Push(asdir); }
else { queue.Enqueue(asdir); }
}
}
}
}
This should answer the question. I've ignored the issue of going through subdirectories, I'm assuming you have that figured out.
Of course, you don't need to have a seperate method for this, but you might find it a useful place to also verify the path is valid, and deal with the other exceptions that you could encounter when calling GetFiles().
Hope this helps.
private string[] GetFiles(string path)
{
string[] files = null;
try
{
files = Directory.GetFiles(path);
}
catch (UnauthorizedAccessException)
{
// might be nice to log this, or something ...
}
return files;
}
private void Processor(string path, bool recursive)
{
// leaving the recursive directory navigation out.
string[] files = this.GetFiles(path);
if (null != files)
{
foreach (string file in files)
{
this.Process(file);
}
}
else
{
// again, might want to do something when you can't access the path?
}
}
I prefer using c# framework functions, but the function i need will be included in .net framework 5.0, so i have to write it.
// search file in every subdirectory ignoring access errors
static List<string> list_files(string path)
{
List<string> files = new List<string>();
// add the files in the current directory
try
{
string[] entries = Directory.GetFiles(path);
foreach (string entry in entries)
files.Add(System.IO.Path.Combine(path,entry));
}
catch
{
// an exception in directory.getfiles is not recoverable: the directory is not accessible
}
// follow the subdirectories
try
{
string[] entries = Directory.GetDirectories(path);
foreach (string entry in entries)
{
string current_path = System.IO.Path.Combine(path, entry);
List<string> files_in_subdir = list_files(current_path);
foreach (string current_file in files_in_subdir)
files.Add(current_file);
}
}
catch
{
// an exception in directory.getdirectories is not recoverable: the directory is not accessible
}
return files;
}

Categories

Resources