Counting photos inside drawable folder [duplicate] - xamarin

In my solution a had a folder with a few files. All this files have the Build Action "Embedded Resource".
With this code I can get a file:
assembly.GetManifestResourceStream(assembly.GetName().Name + ".Folder.File.txt");
But is there any way to get all *.txt files in this folder? A list of names or a method to iterate through them all?

You could check out
assembly.GetManifestResourceNames()
which returns an array of strings of all the resources contained. You could then filter that list to find all your *.txt files stored as embedded resources.
See MSDN docs for GetManifestResourceNames for details.

Try this, returns an array with all .txt files inside Folder directory.
private string[] GetAllTxt()
{
var executingAssembly = Assembly.GetExecutingAssembly();
string folderName = string.Format("{0}.Resources.Folder", executingAssembly.GetName().Name);
return executingAssembly
.GetManifestResourceNames()
.Where(r => r.StartsWith(folderName) && r.EndsWith(".txt"))
//.Select(r => r.Substring(folderName.Length + 1))
.ToArray();
}
NOTE: Uncomment the //.Select(... line in order to get the filename.

have a try with this. here you get all files
string[] embeddedResources = Assembly.GetAssembly(typeof(T)).GetManifestResourceNames();
T is of course your type. so you can use it generic

Just cracked this, use:
Assembly _assembly;
_assembly = Assembly.GetExecutingAssembly();
List<string> filenames = new List<string>();
filenames = _assembly.GetManifestResourceNames().ToList<string>();
List<string> txtFiles = new List<string>();
for (int i = 0; i < filenames.Count(); i++)
{
string[] items = filenames.ToArray();
if (items[i].ToString().EndsWith(".txt"))
{
txtFiles.Add(items[i].ToString());
}
}

Related

how to write code to find element in directory in Linq

How to search for each file in a single directory of xml files and get value of one element?
I tried to loop in Linq:
var files = Directory.GetFiles(C:\Users\valen\Downloads\2019-11-04 apmt, "*.xml", SearchOption.AllDirectories);
foreach (var file in files) {
var doc = XDocument.Load(file);
I need to find shipment element in <>.
It is hard to help when there is very little information about your XML given in OP. Assuming you are searching for Element ShipmentId in your xml files, you could search the Xml File using Linq. For example,
var listOfShipmentIds = new List<string>();
var files = Directory.GetFiles(folderToSearch, "*.xml", SearchOption.AllDirectories);
foreach(var file in files)
{
var dataRead = XDocument.Load(file)
.Root
.DescendantNodes()
.OfType<XElement>()
.Where(x=>x.Name.LocalName.Equals("ShipmentId"))
.Select(x=>x.Value);
listOfShipmentIds.AddRange(dataRead);
}
This would enable you to parse the Xml files and get the value of Element specified.

Pick the latest file based on timestamp provided in the filename

I have to pick the files in order(first file first) from say a folder (C:\Users) and file name has the timestamp in it.
For example below are my files in C:\Users\ and the time stamp is after the first underscore i.e. 20170126102806 in the first file below. I have to loop through files and pick the first file and so on. so out of 5 files below,20170123-000011_20170126101823_AAA is the first file. How do I do this in SSIS?
1.20170123-000011_20170126102806_AAA
2.20170123-000011_20170126103251_AAA
3.20170123-000011_20170126101823_AAA
4.20170123-000011_20170126103305_AAA
5.20170123-000011_20170126102641_AAA
You can act in two ways:
use the foreach loop container to get the list of files, and then populate a database table.
Then, outside the foreach loop, use an Execute SQL to select from that table using an appropriate ORDER BY. Load an object variable with the result set. Then use a second foreach loop to step through the variable object and collect files.
use a Script Task to retrieve the contents of the folder (the list of files) and sort files then load an object variable with the dataset. Then use a foreach loop to step through the variable object to collect files.
I hope this help.
You could use a script task in a For Each Loop. Use the filename returned as the source to load each time.
using System.IO;
public void Main()
{
string filePath = "D:\\Temp";
DirectoryInfo dir = new DirectoryInfo(filePath);
var files = dir.GetFiles("*_AAA");//Or from a variable
DateTime fileCreateDate1 = File.GetCreationTime(filePath + "\\" + files[0]);
if (files.Length >= 2)
{
for (int i = 1; i < files.Length; i++)
{
DateTime fileCreateDate2 = File.GetCreationTime(filePath+ "\\" + files[i]);
if (fileCreateDate1 < fileCreateDate2)
{
fileCreateDate1 = fileCreateDate2;
}
}
}
Dts.Variables["User::FileToLoad"].Value = fileCreateDate1;
Dts.TaskResult = (int)ScriptResults.Success;
}
You will have to remove the file after it was loaded or else it will be loaded each time as it is the oldest or latest file.
There might be a bug or so, but have similar code that works. Just iron it out if needed.

Equivalent of Right() function

Is there an equivalent of right() function that I can use in jquery. I want to get records with fileextension xlsx.
new Guid(context.Documents.Where(T => T.FileName == ".xlsx").Select(T => T.ItemGuid).First().ToString());
something like
select * from document where right(filename,4) = 'xlsx'
I don't want to store the filename in a variable and later manipulate it. I want to be able to directly use it in my where condition. 'Documents' is my table name and "FileName" is a field that holds names of the file that I upload, now I need to get filter only the files that has the extension 'xlsx'. I tried doing
guid temp = new Guid(context.Documents.Where(T => T.FileName.Substring(T.FileName.Length - 4) == ".xlsm").Select(T => T.ItemGuid).First().ToString());
but I get the error "Sequence contains no elements" error.
* Update: Used the EndsWith() to get the information I wanted. This works now:
guid temp = new Guid(context.Documents.Where(T => T.FileName.EndsWith("xlsm")).Select(T => T.ItemGuid).First().ToString());
thanks.
filename.substr(-4)
Using .substr with a negative index will return a substring from the end of the string.
You can use .slice (MDN) function, taking into account that passing a negative value into it makes it cut the string from the end. )
var test = 'filename.xslx';
if (test.slice(-4) === 'xslx') {
alert("Passed");
}
right() is the same as endswith()
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
You might be looking for [name$="value"] selector documented here.
There is not, you can use
var filename = "file.xlsx";
var extension = filename.substr(filename.length - 4);
or to get the characters after the dot, you could use:
var extension = filename.split('.').pop();
Use could javascript match() which provides regex matching.
var filename = 'somefile.xlsx';
var matches = filename.match('/\.xlsx$/i');
if (matches.length > 0) {
// you have a match
}

Read data from txt files - using Linq-Entities?

in my current ASP.net MVC 3.0 project i am stuck with a situation.
I have four .txt files each has approximatly 100k rows of records
These files will be replaced with new files on weekly bases.
I need to Query data from these four text files, I am not able to choose the best and efficient way to do this.
3 ways I could think
Convert these text files to XML on a weekly basis and query it with Linq-XML
Run a batch import weekly from txt to SQL Server and query using Linq-Entities
avoid all conversions and query directly from text files.
Can any one suggest a best way to deal with this situation.
update:
Url of the Text File
I should connect to this file with credentials.
once i connect successfully, I will have the text file as below with Pipeline as Deliminator
This is the text file
Now i have to look up for the field highlighted in yellow and get the data in that row.
Note: First two lines of the text file are headers of the File.
Well As i Found a way my self. Hope this will be useful for any who are interested to get this done.
string url = "https://myurl.com/folder/file.txt";
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["Password"]);
Stream s = request.OpenRead(url);
using (StreamReader strReader = new StreamReader(s))
{
for (int i = 0; i <= 1; i++)
strReader.ReadLine();
while (!strReader.EndOfStream)
{
var CurrentLine = strReader.ReadLine();
var count = CurrentLine.Split('|').Count();
if (count > 3 && CurrentLine.Split('|')[3].Equals("SearchString"))
{
#region Bind Data to Model
//var Line = CurrentLine.Split('|');
//CID.RecordType = Line[0];
//CID.ChangeIdentifier = Line[1];
//CID.CoverageID = Convert.ToInt32(Line[2]);
//CID.NationalDrugCode = Line[3];
//CID.DrugQualifier = Convert.ToInt32(Line[4]);
#endregion
break;
}
}
s.Close();
}
request.Dispose();

Reading the next line using LINQ and File.ReadAllLines()

I have a file which represents items, in one line there's Item GUID followed by 5 lines describing the item.
Example:
Line 1: Guid=8e2803d1-444a-4893-a23d-d3b4ba51baee name= line1
Line 2: Item details = bla bla
.
.
Line 7: Guid=79e5e39d-0c17-42aa-a7c4-c5fa9bfe7309 name= line7
Line 8: Item details = bla bla
.
.
I am trying to access this file first to get the GUIDs of the items meet the criteria provided using LINQ e.g. where line.Contains("line1").. This way I will get the whole line, I will extract the GUID from there, I want to pass this GUID to another function which should access the file "again", find that line (where line.Contains("line1") && line.Contains("8e2803d1-444a-4893-a23d-d3b4ba51baee") and reads the next 5 lines starting from that line.
Is there any efficient way to do so?
I don't think it really makes sense to use LINQ entirely given the requirements of what you need to do and given that the index of the line in the array is fairy integral. I would also recommend doing everything in one pass - opening the file multiple times won't be as efficient as just reading everything once and processing it immediately. As long as the file is structured as well as you describe, this won't be terribly difficult:
private void GetStuff()
{
var lines = File.ReadAllLines("foo.txt");
var result = new Dictionary<Guid, String[]>();
for (var index = 0; index < lines.Length; index += 6)
{
var item = new
{
Guid = new Guid(lines[index]),
Description = lines.Skip(index + 1).Take(5).ToArray()
};
result.Add(item.Guid, item.Description);
}
}
I tried a couple different ways to do this with LINQ but nothing allowed me to do a single scan of the file. For this scenario you're talking about I would go down to the Enumerable level and use the GetEnumerator like this:
public IEnumerable<LogData> GetLogData(string filename)
{
var line1Regex = #"Line\s(\d+):\sGuid=([0123456789abcdefg]{8}-[0123456789abcdefg]{4}-[0123456789abcdefg]{4}-[0123456789abcdefg]{4}-[0123456789abcdefg]{12})\sname=\s(\w*)";
int detailLines = 4;
var lines = File.ReadAllLines(filename).GetEnumerator();
while (lines.MoveNext())
{
var line = (string)lines.Current;
var match = Regex.Match(line, line1Regex);
if (!match.Success)
continue;
var details = new string[detailLines];
for (int i = 0; i < detailLines && lines.MoveNext(); i++)
{
details[i] = (string)lines.Current;
}
yield return new LogData
{
Id = new Guid(match.Groups[2].Value),
Name = match.Groups[3].Value,
LineNumber = int.Parse(match.Groups[1].Value),
Details = details
};
}
}

Resources