SearchOption.AllDirectories and ignore access errors? - list

string[] files = Directory.GetFiles(tb_dir.Text, tb_filter.Text, SearchOption.AllDirectories);
I'm trying to search through a directory and all sub directory to find some file. I keep running into an error with the current code that the second it sees something it can't get into it breaks
In this application that doesn't matter i would rather it just move on. Is there anyway to bypass this code from dumping out everytime?
Thanks
Crash893

You could do something like this:
List<string> GetFiles(string topDirectory, string filter)
{
List<string> list = new List<string>();
list.AddRange(Directory.GetFiles(topDirectory, filter));
foreach (string directory in Directory.GetDirectories(topDirectory))
{
list.AddRange(GetFiles(directory));
}
return list;
}
and call it with:
List<string> files = GetFiles(tb_dir.Text, tb_filter.Text);
You could convert the list of files into an array, of course.
You would have to add try catch blocks to handle the UnauthorizedAccessException.

Related

How do I use groovy/Gradle DSL to get a list of directories matching a pattern?

The Gradle sonar plugin has a sonar.junit.reportPaths property that needs to be a comma-separated list of directories containing the JUnit test results files.
In our case, the directories match the pattern "^.*/build/test-results/(test|(component|integration)Test)/.*$".
We wanted to generate that list using fileTree includes/matching.
But it appears that fileTree:
Returns only files, not directories.
Is limited to ant-style file globbing, not full regular expressions.
After flailing around for way longer than we should have spent on it, we finally gave up and wrote it in Java:
def junitResults() {
Set<String> testDirs = new LinkedHashSet<>()
for (File file : files(fileTree(dir: rootDir, include: "**/build/test-results/**"))) {
testDirs.add(file.getAbsolutePath().replaceAll("/build/test-results/(test|(component|integration)Test)/.*", "/build/test-results/\$1"))
}
return testDirs.toArray(new String[testDirs.size()]);
}
That has the advantage of actually working, but it looks idiosyncratic.
Does someone know how to replace that with normal-looking groovy/Gradle DSL?
Maybe something with eachDirMatch() like this
file('path/build/test-results/.').eachDirMatch(/(test|(component|integration)Test)/) { dir ->
println dir.getPath()
}
wp78de, your answer pointed me in the right direction (use file, not fileTree):
def junitResultsDirs() {
def dirs = []
rootDir.eachDirRecurse { dir ->
if (dir.absolutePath.matches("^.*/build/test-results/(test|(component|integration)Test)\$")) {
dirs << dir
}
}
return dirs;
}

C# UWP textfile to list of strings

I'm creating a UWP application (latest windows IoT) for my raspberry.
I'm trying to get a list of strings from a .txtfile located in the project folder under a map called Words.
This is my code so far.
public async void GenereerGokWoord(int character)
{
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appx:///Words//5-letterwoorden.txt")
);
}
By setting a breakpoint at the end of the } I can confirm that this code can find the .txt file.
But now I don't know how to get a list of strings from this point on.
The .txt file looks like things
word 1
word 2
word 3
If you want contents of file as a List with each line as an Item, Use FileIO.ReadLinesAsync()
IList<string> data = await FileIO.ReadLinesAsync(file);
List<string> finallist = data.ToList();
Your finallist should contain all words as List.

Get filename in Dynamics Ax

I need to extract a file name from complete path and I see it strange that I when I split the path, I need to iterate through the list to get the file name. Why can't I just get the value simply by calling myList(3) as in DotNet, instead of having to instantiate an iterator, then loop through the records.
Here is my code;
List strlist=new List(Types::String);
strlist = strSplit(CompletePath, #"\");
After doing this I should have a list of all the different parts.
Is there any simple form to read the list, like FileName = strlist[2]; instead of having to do the below;
iterator = new ListIterator(strlist);
while(iterator.more())
{
FileName = iterator.value();
if (_Value == "myFile")
{
_NotFound=boolean::false;
}
Here again, if at that very moment, I don't know the file name, how do I check?
Global::fileNameSplit(fileName)
returns a container [path, file name, extension]
Should be used over the .NET methods recommended by Matej.
Use System.IO.Path::GetFileName(CompletePath) or System.IO.Path::GetFileNameWithoutExtension.

C++/CX - GetFileAsync throws breakpoint error

I am trying to open a xml file from my Assets folder, but unfortunately I am only able to open my xml file by using a FileOpenPicker which is not the most ideal situation when I have to constantly fetch my xml file, without disturbing the user of course.
FileOpenPicker^ openPicker = ref new FileOpenPicker();
openPicker->ViewMode = PickerViewMode::List;
openPicker->SuggestedStartLocation = PickerLocationId::Desktop;
openPicker->FileTypeFilter->Append(".xml");
task<StorageFile^>(
openPicker->PickSingleFileAsync()).then([this](StorageFile^ file) {
if (nullptr != file) {
task<Streams::IRandomAccessStream^>(file->OpenAsync(FileAccessMode::Read)).then([this](Streams::IRandomAccessStream^ stream)
{
IInputStream^ deInputStream = stream->GetInputStreamAt(0);
DataReader^ reader = ref new DataReader(deInputStream);
reader->LoadAsync(stream->Size);
String^ strXml = reader->ReadString(stream->Size);
});
}
});
I am now trying to reconstruct this code into a code which loads up my xml file without letting the user choose. I tried the following approach:
String^ xmlFile = "Assets\MyXmlFile.xml";
StorageFolder^ InstallationFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;
task<StorageFile^>(
InstallationFolder->GetFileAsync(xmlFile)).then([this](StorageFile^ file) {
if (nullptr != file) {
task<Streams::IRandomAccessStream^>(file->OpenAsync(FileAccessMode::Read)).then([this](Streams::IRandomAccessStream^ stream)
{
IInputStream^ deInputStream = stream->GetInputStreamAt(0);
DataReader^ reader = ref new DataReader(deInputStream);
reader->LoadAsync(stream->Size);
String^ strXml = reader->ReadString(stream->Size);
stream->FlushAsync();
});
}
});
I think I get errors at the GetFileAsync which I am not able to solve and I am asking you, the community to try and help me.
Your code worked for me with one modification: the xmlFile string contains a backslash that needs to be escaped:
String^ xmlFile = "Assets\\MyXmlFile.xml";
Note also that if you just right-clicked "Assets" in your project and chose "Add new item", that item may have ended up in your root project folder (which is the default). If you want it to be deployed to the Assets subfolder it will need to physically live there on disk in the assets subdirectory, not just be in the Assets filter. (Unlike in C#, the C++ project "folders" are actually filters and do not reflect physical directory location.)

PlayFramework 2.0 - Not able to call functions from other templates

I want to place some helper functions in another file, since they will be overly reused. I took the Computer-Databse sample's listing file:
https://github.com/playframework/Play20/blob/master/samples/scala/computer-database/app/views/list.scala.html
I created a new file, called "listing.scala.html" under the app/views package, and moved the #link function from the original file to it. This new file looks like this:
#(currentSortBy: String, currentOrder: String, currentFilter: String)
#****************************************
* Helper generating navigation links *
****************************************#
#link(newPage:Int, newSortBy:String) = #{
var sortBy = currentSortBy
var order = currentOrder
if(newSortBy != null) {
sortBy = newSortBy
if(currentSortBy == newSortBy) {
if(currentOrder == "asc") {
order = "desc"
} else {
order = "asc"
}
} else {
order = "asc"
}
}
// Generate the link
routes.Application.listPerfil(newPage, sortBy, order, currentFilter)
}
So, on my original file, I replaced the #link call, with this one:
#title
And the problem is, when I try to compile I get this error:
value link is not a member of play.api.templates.Html
But according to the documentation (http://www.playframework.org/documentation/2.0.4/ScalaTemplateUseCases) it seems to be ok.
Any guess?
Play's templates aren't the best place for placing advanced conditions, most probably you'll get better flexibility by processing it in some controller (or other method) which will return you only required link
ie.:
#title
In your case proposed link(...) function of Application controller can also return a reverse-route.
Keep in mind that including other templates is best option for repeating blocks of HTML but sometimes it's hard to get specified string (mainly because of not trimmed spaces). As you can see there is also problem with calling nested functions. Most probably you can generate whole A tag in the listing.scala.html however using it isn't comfortable enough (IMHO).