I have two files in my directory, I have created an array and each of them have an unique postfix. In this array, there are two files. I want to the program to select the latest file 20160906. If there are 3rd file (20170906) then I want to program to select this filename. Help would be appreciated.
myArray:
[0] = myFile20150906
[1] = myFile20160906
[2] = myFile20170906
expected Result:
string latestFile = 'myFile20170906'
As long as your strings are all in the format myFileYYYYMMDD then comparing them as strings will be the same as comparing them in date order.
Because of this, you can use Enumerable.Max() to find the latest date, like so:
string latest = myArray.Max();
Note that Enumerable.Max() works with any type that implements IComparable or IComparable<T>, which includes string.
Related
I d like to create a blind test generator with a script using Sony vegas 14. For this I must make my script in C#.
I don’t have many experiences in C# so maybe my problem is a very basic one.
To do my script I must use a library class (.dll) and execute my script by Sony vegas. To test my code easily I create a console app where I try my code and can easily print in the console what my code does.
For my program y need to get the path of all subdirectory in a Directory in a string.
My problem is the next one.
the command "Directory.GetDirectories" don't work
When I use the next code to check what in my array/list I get a coherent result if I use it in the console app version on my script (the number of subdirectories in my directory)
string[] dirs = Directory.GetDirectories(myDirectorypath, "", SearchOption.TopDirectoryOnly);// get all directory path in dirs
Console.WriteLine("the number of element in your array is "+ dirs.Length);
List<string> listdedossier = new List<string>(dirs); // convert the array in a list
Console.WriteLine("the number of element in your list is " + listdedossier.Count);
But when in paste my code in my dll project nothing is written in my array or my list. I notice this because when I want to print the number of elements in the list /array that return me 0
.
do you have any idea of what happen i my code?
thanks
You should check the online Microsoft documentation for GetDirectories. The 2nd argument is supposed to be a pattern to search for that conforms to Windows file name patterns. Essentially, all or part of a file name is allowed with * being a wildcard (The .* from regex meaning "match any character any number of times") and ? being a single character wildcard (regex .). You are providing an empty string, so you get nothing back. The pattern *.exe will match all executables in a folder (if you are using GetFiles, while the pattern pattern* matches any files/folders that start with pattern. If you want all directories, do this:
string[] dirs = Directory.GetDirectories(myDirectoryPath, "*", SearchOption.TopDirectoryOnly);
Next point, the path you provide can be either a relative path (e.g., "relative\path\to\folder"), an absolute path (e.g., "D:\path\to\folder"), or a fully qualified domain name (FQDN, e.g. "\servername.gov.edu.com\drive$\path\to\folder"). If you supply a relative path, you'll need to look up Windows' rules for path resolution. It is very easy using a relative path to search the wrong folder, or even a non-existent location (though you should get an exception in that case). Also remember: Windows path names are NOT case-sensitive.
Finally, when writing text with arguments, I HIGHLY recommend you use this format:
Console.WriteLine("The number of elements in your array is {0}", dirs.Length);
This uses a place holder in the string itself which has a numeric value in it. The number indicates what argument after the format string to use (0 is the first argument after the format string). You can use as many placeholders as you want, and use the same place holder in multiple locations. This is a more type-safe way to doing string printing in C# than using the + operator, which requires that an operator be defined that takes a string and whatever type you provided. When you use placeholders, WriteLine will use the built-in ToString method which is defined for all types in the Object class. Placeholders will always work, while using + will only sometimes work.
I am having some problems with a quite easy task - i feel like im missing something very obvious here.
I have a .csv file which is semicolon seperated. In this file are several numbers that contain dots like "1.300" but there are also dates included like "2015.12.01". The task is to find and delete all dots but only those that are in numbers and not in dates. The dates and numbers are completely variable and never at the same position in the file.
My question now: What is the 'best' way to handle this problem?
From a programmers point of view: Is it a good solution to just split at every semilicon, count the dots and if there is only one dot, delete it? This is the only way to solve the problem i could think of by now.
Example source file:
2015.12.01;
13.100;
500;
1.200;
100;
Example result:
2015.12.01;
13100;
500;
1200;
100;
If you can rely on the fact that dates have two dots and numbers just one, you can use that as a filter:
string s = "123.45";
if (s.Count(x => x == '.') == 1)
{
s = s.Replace(".", null);
}
The source file looks like a valid file generated by a program running on a machine whose locale uses . as the thousand separator (most of Europe does) and date separator (German locales only I think). Such locales also use ; as the list separator.
If the question was only how to parse such dates, numbers, the answer would be to pass the proper culture to the parse function, eg: decimal.Parse("13.500",new CultureInfo("de-at")) would return 13500. The actual issue though is that the data must be fed to another program that uses . as the decimal separator.
The safest option would be to change the locale used by the exporting program, eg change the thread CultureInfo if the exporter is a .NET program, the locale in an SSIS package etc, to a locale like en-gb to export with . and avoid the weird date format. This assumes that the next program in the pipeline doesn't use German for the date, English for numbers
Another option would be to load the text, parse the fields using the proper locale then export them in the format required by the next program.
Finally, a regular expression could be used to match only the numeric fields and remove the dot. This can be a bit tricky and depends on the actual contents.
For example (\d+)\.(\d{3}) can be used to match numbers if there is only one thousand separator. This can fail if some text field contains similar values. Or ;(\d+)\.(\d{3}); could match only a full field, except the first and last fields, eg:
Regex.Replace("1.457;2016.12.30;13.000;1,50;2015.12.04;13.456",#";(\d+)\.(\d{3});",#"$1$2;")
produces :
1.457;2016.12.3013000;1,50;2015.12.04;13.456
A regular expression that would match either numbers between ; or the first/last field could be
(^|;)(\d+)\.(\d{3})(;|$)
This would produce 1457;2016.12.30;13000;1,50;2015.12.04;13456, eg:
var data="1.457;2016.12.30;13.000;1,50;2015.12.04;13.456";
var pattern=#"(^|;)(\d+)\.(\d{3})(;|$)";
var replacement=#"$1$2$3$4";
var result= Regex.Replace(data,pattern,replacement);
The advantage of a regex over splitting and replacing strings is that it's a lot faster and more memory efficient. Instead of generating temporary strings for each split, manipulation, a Regex only calculates indexes in the source. A string object is generated only when you request the final text result. This results in far fewer allocations and garbage collections.
Even in medium-sized files this can result in 10x better performance
I wouldn't rely on the number of dots as mistakes can be made.
You can use the double.TryParse to safely test if the string is a number
var data = "2015.12.01;13.100;500;1.200;100;";
var dataArray = data.Split(';');
foreach (var s in dataArray)
{
double result;
if(double.TryParse(s,out result))
// implement your logic here
Console.WriteLine(s.Replace(".",string.Empty));
}
I am in need of parsing an array or characters that is a fixed length but can have just about any combination of letter or number. My 50 digit array looks like this: NL1NAMEOFCO-B032144221111000100600000-A35499001
This array represents a vast combination of settings within our product. I need to extract all reference designators in the array. The first 3 characters represent a particular model NL1, the next 8 characters represent a company NAMEOFCO. The ‘-‘ will always be in the same location. The B (digit 13) represents some value, etc, etc. Also, some values are represented by 2 digits. Digits 20 & 21 (which store the value 22), represent some specific settings.
So by now you get the idea. I can parse the array and extract the values I need by using the following code:
String Company = ConfigCode[3].ToString() +
ConfigCode[4].ToString() +
ConfigCode[5].ToString() +
ConfigCode[6].ToString() +
ConfigCode[7].ToString() +
ConfigCode[8].ToString() +
ConfigCode[9].ToString() +
ConfigCode[10].ToString();
This works without any problems, but to me, there should be an easier way of doing this. I would have thought the following would work, but it does not.
String Company = ConfigCode[3..10].ToString();
Can someone explain to me why it doesn’t work and what would be a better way of extracting the information I need?
Thanks!
I believe that String.Substring method is what you're looking for. The signature for the overloaded method you're looking for is:
public string Substring(
int startIndex,
int length
)
The documentation for it is here: http://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx
For example, your Company name would be (going by the description of a character length of 8):
string CompanyName = configCode.Substring(3, 8);
Like mentioned before, you can use the Substring extension method like so:
String Company = ConfigCode.Substring(3, 8);
The square-bracket operators for strings, like in ConfigCode[3], actually return individual chars at that specific index. And C# isn't as pretty as other programming languages where stuff like array[3..10] actually gives you a portion of an array (or in this case, a string).
I am creating C# Windows Form that retrieves files from shared drives as email attachments. I am trying to automate the file retrieval process, but the filepaths available to me vary according to the date. For example:
V:\....\Dec-03\filename12-3-2013.xml
J:\.....\December\filename12-4-2013
I have the filepath stored as string from a textbox, but since the path varies slightly day-to-day, I've been trying to figure out how automate this process. In the past I've used VBA code where I've concatenated method calls into the string like this
"..." & Day(Date) & "..."
(I replaced the ampersand with the plus sign of course for C#)
But this just gets me an illegal characters in path Argument exception.
I am using a check for filedate and taking a a specific filepath through a textbox. I want particular files that are being updated in monthly folders and the filename contains a date. I want to grab the ones with today's date or yesterday's date, but some have no date in the filename or directory at all. Since there isn't a lot of consistency, I would love to enter code
"+ DateTime.Now.ToString() +"
in the textbox per individual filepath as I load them via the form and have the program execute like I've done with some VBA code, but I get Illegal characters with the double quotes in the middle of a filepath. Is there some work around or will I need to create fixes for every particular pattern?
Use System.IO.Path.Combine(...) to handle chaining directories together (it takes care of extra slashes for you). In your combine, use String.Format(SomeFormatString, token1value, toke2value, etc.) to give you the name you were wanting.
C# uses + to append strings instead of & in older VB.
"My Date: " + DateTime.Now.ToString("MM/dd/yyyy")
An example of this with the String.Format I showed above would be
string.Format("My Date: {0}", DateTime.Now.ToString("MM/dd/yyyy"))
If I'm following what you're saying about Day(Date), you might try some thing like this in C#:
MyObject.SomeMethod("some string " + dateValue.ToString("ddd") + " more string data");
Where dateValue is a DateTime object and the "ddd" parameter tells the ToString method to return a three character abbreviation of the day of the week (e.g. 'Wed').
For more information on using ToString with DateTime objects to extract various parts of the date, see
http://msdn.microsoft.com/en-us/library/bb762911(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
The ToString overload of the DateTime structure will allow you to format a date as the Month name, etc.
var x = DateTime.Today.ToString("MMMM"); // December
You can include other characters in the format string as well, for example to get Dec-19 you can use:
var x = DateTime.Today.ToString("MMM-dd"); // Dec-19
TyCobb's answer covers combining the formatted date into a path using Path.Combine (which I generally recommend).
You can also use String.Format to insert a formatted value into a string, which is often easier to read and leads to fewer mistakes. For example, to generate your first example, you could use the following:
var path =
String.Format("V:....\{0:MMM-dd}\filename{0:M-d-yyyy}.xml", DateTime.Today);
I am making an SQL Query that brings back a list of files and their paths. They have different file paths and different file names ofc.
The file names are dates and time in the following format:
YearMonthDayHourMinuteSeconds
What I need to do is take the filepath that has the latest date and time, strip off everything except the date and time part and then using the date and time re-query the database.
I have very few ideas on how to do this.
EDIT: The date will be changing and I need to take the latest when ever the program is run.
My first idea would be to treat everything the query returns as strings
When you get your result set, you could iterate through it storing the record you want in a string or multiple strings. You can compare strings with firststring.Compare(secondstring) it returns 1 or greater if the secondstring is alfabeticaly after firststring.
Then use substring to extract the part of the string you want
string inf = latestdate.Substring(startindex, length);
Hope this helps
use the standard .NET file operation libraries
something like:
using System.IO;
...
string myFileNameWithFullPath;
...
DateTime newDate = DateTime.Parse(Path.GetFileName(myFileNameWithFullPath));
string tmps = Path.GetFileNameWithoutExtension(filenameFromSQL);
DateTime myDateTime = DateTime.Parse(String.Format("{1}/{2}/{0}",
tmps.Substring(0,4), tmps.Substring(5,2), tmps.Substring(7,2));