Any string in some method e.g. File.Exist() - c#

How can I make, in File.Exist method put some filename that contains some numbers? E.g "file1.abc", "file2.abc", "file3.abc" etc. without using Regex?

Are you trying to determine if various files match the pattern fileN.abc where N is any number? Because File.Exists can't do this. Use Directory.EnumerateFiles instead to get a list of files that match a specific pattern.

Do you mean something like
for (int i = 1; i < 4; i++)
{
string fileName = "file" + i.ToString() + ".abc";
if (File.Exists(fileName))
{
// ...
}
}

new DirectoryInfo(dir).EnumerateFiles("file*.abc").Any();
or
Directory.EnumerateFiles(dir, "file*.abc").Any();

In the unix world, it is called globbing. Maybe you can find a .NET library for that? As a starting point, check out this post: glob pattern matching in .NET

Below is the code snap which will return all files with name prefix "file" with any digits whose format looks like "fileN.abc", even it wont return with file name "file.abc" or "fileX.abc" etc.
List<string> str =
Directory.EnumerateFiles(Server.MapPath("~/"), "file*.abc")
.Where((file => (!string.IsNullOrWhiteSpace(
Path.GetFileNameWithoutExtension(file).Substring(
Path.GetFileNameWithoutExtension(file).IndexOf(
"file") + "file".Length)))
&&
(int.TryParse(Path.GetFileNameWithoutExtension(file).Substring(
Path.GetFileNameWithoutExtension(file).IndexOf("file") + "file".Length),
out result) == true))).ToList();
Hope this would be very helpful, thanks for your time.

Related

Taking the last Substring of a string in C#

I have a string
"\uploads\test1\test2.file"
What's the method to get just "test2.file"?
What I have in my mind is to get the last index of "\" and then perform a string.substring(last index of "\") command on it?
Is there a method that takes just the word after the last "\"?
Use the method Path.GetFileName(path); in System.IO namespace, it is much more elegant than doing string operations.
You could use LINQ:
var path = #"\uploads\test1\test2.file";
var file = path.Split('\\').Last();
You might want to validate the input, if you're concerned about path potentially being null or whatnot.
You could do something like this:
string path = "c:\\inetpub\\wwwrroot\\images\\pdf\\admission.pdf";
string folder = path.Substring(0,path.LastIndexOf(("\\")));
// this should be "c:\inetpub\wwwrroot\images\pdf"
var fileName = path.Substring(path.LastIndexOf(("\\"))+1);
// this should be admin.pdf
For more take a look at here How do I get the last part of this filepath?
Hope it helps!
You can use the Split method:
string myString = "\uploads\test1\test2.file";
string[] words = myString.Split("\");
//And take the last element:
var file = words[words.lenght-1];
using linq:
"\uploads\test1\test2.file".Split('\\').Last();
or you can do it without linq:
string[] parts = "\uploads\test1\test2.file".Split('\\');
last_part=parts[parts.length-1]

How to properly split a CSV using C# split() function?

Suppose I have this CSV file :
NAME,ADDRESS,DATE
"Eko S. Wibowo", "Tamanan, Banguntapan, Bantul, DIY", "6/27/1979"
I would like like to store each token that enclosed using a double quotes to be in an array, is there a safe to do this instead of using the String split() function? Currently I load up the file in a RichTextBox, and then using its Lines[] property, I do a loop for each Lines[] element and doing this :
string[] line = s.Split(',');
s is a reference to RichTextBox.Lines[].
And as you can clearly see, the comma inside a token can easily messed up split() function. So, instead of ended with three token as I want it, I ended with 6 tokens
Any help will be appreciated!
You could use regex too:
string input = "\"Eko S. Wibowo\", \"Tamanan, Banguntapan, Bantul, DIY\", \"6/27/1979\"";
string pattern = #"""\s*,\s*""";
// input.Substring(1, input.Length - 2) removes the first and last " from the string
string[] tokens = System.Text.RegularExpressions.Regex.Split(
input.Substring(1, input.Length - 2), pattern);
This will give you:
Eko S. Wibowo
Tamanan, Banguntapan, Bantul, DIY
6/27/1979
I've done this with my own method. It simply counts the amout of " and ' characters.
Improve this to your needs.
public List<string> SplitCsvLine(string s) {
int i;
int a = 0;
int count = 0;
List<string> str = new List<string>();
for (i = 0; i < s.Length; i++) {
switch (s[i]) {
case ',':
if ((count & 1) == 0) {
str.Add(s.Substring(a, i - a));
a = i + 1;
}
break;
case '"':
case '\'': count++; break;
}
}
str.Add(s.Substring(a));
return str;
}
It's not an exact answer to your question, but why don't you use already written library to manipulate CSV file, good example would be LinqToCsv. CSV could be delimited with various punctuation signs. Moreover, there are gotchas, which are already addressed by library creators. Such as dealing with name row, dealing with different date formats and mapping rows to C# objects.
You can replace "," with ; then split by ;
var values= s.Replace("\",\"",";").Split(';');
If your CSV line is tightly packed it's easiest to use the end and tail removal mentioned earlier and then a simple split on a joining string
string[] tokens = input.Substring(1, input.Length - 2).Split("\",\"");
This will only work if ALL fields are double-quoted even if they don't (officially) need to be. It will be faster than RegEx but with given conditions as to its use.
Really useful if your data looks like
"Name","1","12/03/2018","Add1,Add2,Add3","other stuff"
Five years old but there is always somebody new who wants to split a CSV.
If your data is simple and predictable (i.e. never has any special characters like commas, quotes and newlines) then you can do it with split() or regex.
But to support all the nuances of the CSV format properly without code soup you should really use a library where all the magic has already been figured out. Don't re-invent the wheel (unless you are doing it for fun of course).
CsvHelper is simple enough to use:
https://joshclose.github.io/CsvHelper/2.x/
using (var parser = new CsvParser(textReader)
{
while(true)
{
string[] line = parser.Read();
if (line != null)
{
// do something
}
else
{
break;
}
}
}
More discussion / same question:
Dealing with commas in a CSV file

Directory Exists with Path Combine vs String Concatenation

So as I am building a Folder/File checking conditional, and a co-worker says it is "better" to use Path.Combine:
string finalPath = Path.Combine(folder, "file.txt");
as opposed to the way I was doing it with
string finalPath = folder + "\\file.txt";
Any sound reasoning this is "better?"
It's an interesting question;
You could, of course, write something like:
string finalPath = String.Format("{0}\\file.txt", folder);
To achieve the result you want.
Using ILSpy, though, lets see why Path.Combine is better.
The overload you are calling is:
public static string Combine(string path1, string path2)
{
if (path1 == null || path2 == null)
{
throw new ArgumentNullException((path1 == null) ? "path1" : "path2");
}
Path.CheckInvalidPathChars(path1, false);
Path.CheckInvalidPathChars(path2, false);
return Path.CombineNoChecks(path1, path2);
}
The advantages are obvious; firstly, the function checks for null values and throws the appropriate exception. Then it checks for illegal characters in either of the arguments, and throws an appropriate exception. Once it is satisfied, it calls Path.CombineNoChecks:
private static string CombineNoChecks(string path1, string path2)
{
if (path2.Length == 0)
{
return path1;
}
if (path1.Length == 0)
{
return path2;
}
if (Path.IsPathRooted(path2))
{
return path2;
}
char c = path1[path1.Length - 1];
if (c != Path.DirectorySeparatorChar && c != Path.AltDirectorySeparatorChar && c != Path.VolumeSeparatorChar)
{
return path1 + Path.DirectorySeparatorChar + path2;
}
return path1 + path2;
}
The most interesting thing here are the characters it supports;
Path.DirectorySeparatorChar = "\\"
Path.AltDirectorySeparatorChar = "/"
Path.VolumeSeparatorChar = ":"
So it will also support paths where the separator is the wrong way around (like from a urn file://C:/blah, too)
In short, it's better because it gives you validation, a degree of portability (the 3 constants shown above can be defined on a per framework-OS basis), and has support for more than one type of path that you commonly encounter.
try these two to see the difference.... It can handle URI and standard paths. So always use Path.Combine.
Console.WriteLine(Path.Combine(#"file:///c:/temp/", "x.xml"));
Output file:///c:/temp/x.xml
Console.WriteLine(Path.Combine(#"C:\test", "x.xml"));
Output C:\test\x.xml
Yes, it's more portable in the case that the file-path separator is different to \
First you can use this notation #"\file.txt instead of "\\file.txt";
Second, let .Net care about fixing the path. There is a reason we have it.
You can be 100% sure that you've done it correctly but if you start combining paths by hand everywhere in your code, there is always a chance to create bugs.
A simple example.
User enters a path and you want to create a subfolder named temp there. What will you do?
If no backslash at the end, add one, else do this, otherwise do the other... etc.
With Path.Combine() you don't have to do checking. You can concentrate on the actual logic of your application.
One really could thing plus the other comments, it is the capability to combine many parts of the directory you want to create.
As an example is this:
Path.Combine(root, nextFolder, childfolder, file);
It supports many characters as it receives an array of string, so it is capable to create the right directory in one single executed line.
Regards,

Using Substring in C# reverse

And I have filepath say "\ABC\ABX\file.pdf".
How can I get only the folder path i.e. "\ABC\ABX\" using substring any other way.
Thank you in advance.
Use System.IO.Path class
var dir = Path.GetDirectoryName(#"\ABC\ABX\file.pdf");
You're looking for Path.GetDirectoryName
var directoryOnly = System.IO.Path.GetDirectoryName(#"\ABC\ABX\file.pdf")
Live example: http://rextester.com/WDVD42852
You can do this using a combination of Substring and LastIndexOf:
string path = #"\ABC\ABX\file.pdf";
string directory = path.Substring(0, path.LastIndexOf(#"\") + 1);
It would also be ideal to add a check to ensure that the path even contains a \, and because of the + 1 you would also want to check that the \ is not already the last character. Of course though, it would be better to not need such string manipulation in the first place, but I don't know what your exact scenario is
string result = test.Substring(0, test.LastIndexOf("\\") + 1);
There are nicer ways to do this using System.IO, but purely string manipulation:
string path = #"\ABC\ABX\file.pdf";
string folder = path.Substring(0, path.LastIndexOf(#"\"));

How to cut a string

I have a strings like
"/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben"
And I need only "175_Jahre_STAEDTLER_Faszination_Schreiben" where "root" is separator. How can I do this?
"/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben".Split("/root/")[1] should give you "175_Jahre_STAEDTLER_Faszination_Schreiben"
Another method:
String newstring = file_path.Substring(file_path.LastIndexOf('/') + 1);
Check out the System.IO.Path methods - not quite files and folders but with the / delimiter it just might work!
If you're looking to extract a part of a string based on an overall pattern, regular expressions can be a good alternative in some situations.
string s = "/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben";
Regex re = new Regex(#"/root/(?<goodPart>\w+)$");
Match m = re.Match(s);
if (m.Success) {
return m.Groups["goodPart"].ToString();
}
string s = "/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben";
string separator = "root";
string slash = "/";
int idx = s.IndexOf(separator);
string result = s.SubString(idx + separator.Length + slash.Length);
Use String.Split to separate the string with "root" as the separator. Then use the second element of the resulting array.
If you need to find a relative path based on a base path (which it sounds like what the problem you are trying to solve is, or at least a generalization of your problem) you can use the System.Uri class. It does have it's limitations, however. The cleanest and most correct way to find a relative path is to use DirectoryInfo. With DirectoryInfo you can "walk" the directory tree (backwards or forwards) and build a hierarchy based on that. Then just do a little set manipulation to filter out duplicates and what you have left is your relative path. There are some details, like adding ellipses in the correct place, etc..., but DirectoryInfo is a good place to start in order to parse paths based on the current OS platform.
FYI - I just finished writing a component here at work to do just that so it's fairly fresh in my mind.
string s = "/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben";
int li = s.LastIndexOf("root/");
s = s.Substring(li + 5, s.Length - 1 - (li + 4));
MessageBox.Show(s);

Categories

Resources