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]
Related
So I have a few file extensions in my C# projects and I need to remove them from the file name if they are there.
So far I know I can check if a Sub-string is in a File Name.
if (stringValue.Contains(anotherStringValue))
{
// Do Something //
}
So if say stringValue is test.asm, and then it contains .asm, I want to somehow remove the .asm from stringValue.
How can I do this?
if you want a "blacklist" approach coupled with the Path library:
// list of extensions you want removed
String[] badExtensions = new[]{ ".asm" };
// original filename
String filename = "test.asm";
// test if the filename has a bad extension
if (badExtensions.Contains(Path.GetExtension(filename).ToLower())){
// it does, so remove it
filename = Path.GetFileNameWithoutExtension(filename);
}
examples processed:
test.asm = test
image.jpg = image.jpg
foo.asm.cs = foo.asm.cs <-- Note: .Contains() & .Replace() would fail
You can use Path.GetFileNameWithoutExtension(filepath) to do it.
if (Path.GetExtension(stringValue) == anotherStringValue)
{
stringValue = Path.GetFileNameWithoutExtension(stringValue);
}
No need for the if(), just use :
stringValue = stringValue.Replace(anotherStringValue,"");
if anotherStringValue is not found within stringValue, then no changes will occur.
One more one-liner approach to getting rid of only the ".asm" at the end and not any "asm" in the middle of the string:
stringValue = System.Text.RegularExpressions.Regex.Replace(stringValue,".asm$","");
The "$" matches the end of the string.
To match ".asm" or ".ASM" or any equivlanet, you can further specify Regex.Replace to ignore case:
using System.Text.RegularExpresions;
...
stringValue = Regex.Replace(stringValue,".asm$","",RegexOptions.IgnoreCase);
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(#"\"));
I have a file name dayhappy_02_02345.csv
How do I get the 02 part out to be used in a variable and also how do I get the 02345 part so that I can pass these 2 values into a variable for a function.
Using c#.
I have looked at GetFileName but this gets either the filename, the extention or the full file name only.
Thanks
Ste
For that specific file name,
string sData = "dayhappy_02_02345.csv";
string[] sArr = sData.split('_');
string sPart1 = sArr[1];
string sPart2 = sArr[2];
Will do, but that's a special case, will work only on file names of this type
Get the file name as you've already figured out, then use String.Split() to get the individual pieces.
You have to use Regex:
var match = new Regex(#".*_(\d+)_(\d+)").Match(Path.GetFileNameWithoutExtension(fileNAme));
var v02 = match.Groups[0].Value;
var v02345 = match.Groups[1].Value;
If i am using C# and i have a string coming in from a database like this:
\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML
And i only want this part of the string:
1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML
How can i get this string if there is more than one "\" symbol?
You can use the LastIndexOf() method of the String class:
string s = #"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA.xml";
Console.Out.WriteLine(s.Substring(s.LastIndexOf('\\') + 1));
Hope, this helps.
Use String.Split to split string by parts and then get the last part.
Using LINQ Enumerable.Last() :
text.Split('\\').Last();
or
// todo: add null-empty checks, etcs
var parts = text.Split('\\');
strign lastPart = parts[parts.Length - 1];
You can use a combination of String.LastIndexOf("\") and String.Substring(lastIndex+1). You could also use (only in the sample you provided) Path.GetFileName(theString).
string[] x= line.Split('\');
string goal =x[x.Length-1];
but linq will be easier
You can use regex or split the string by "\" symbol and take the last element of array
using System.Linq;
public class Class1
{
public Class1()
{
string s =
#"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML";
var array = s.Split('\\');
string value = array.Last();
}
}
newstring = string.Substring(string.LastIndexOf(#"\")+1);
It seems like original string is like filePath.
This could be one easy solution.
string file = #"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA.xml";
string name = System.IO.Path.GetFileName(file);
My strings look like that: aaa/b/cc/dd/ee . I want to cut first part without a / . How can i do it? I have many strings and they don't have the same length. I tried to use Substring(), but what about / ?
I want to add 'aaa' to the first treeNode, 'b' to the second etc. I know how to add something to treeview, but i don't know how can i receive this parts.
Maybe the Split() method is what you're after?
string value = "aaa/b/cc/dd/ee";
string[] collection = value.Split('/');
Identifies the substrings in this instance that are delimited by one or more characters specified in an array, then places the substrings into a String array.
Based on your updates related to a TreeView (ASP.Net? WinForms?) you can do this:
foreach(string text in collection)
{
TreeNode node = new TreeNode(text);
myTreeView.Nodes.Add(node);
}
Use Substring and IndexOf to find the location of the first /
To get the first part:
// from memory, need to test :)
string output = String.Substring(inputString, 0, inputString.IndexOf("/"));
To just cut the first part:
// from memory, need to test :)
string output = String.Substring(inputString,
inputString.IndexOf("/"),
inputString.Length - inputString.IndexOf("/");
You would probably want to do:
string[] parts = "aaa/b/cc/dd/ee".Split(new char[] { '/' });
Sounds like this is a job for... Regular Expressions!
One way to do it is by using string.Split to split your string into an array, and then string.Join to make whatever parts of the array you want into a new string.
For example:
var parts = input.Split('/');
var processedInput = string.Join("/", parts.Skip(1));
This is a general approach. If you only need to do very specific processing, you can be more efficient with string.IndexOf, for example:
var processedInput = input.Substring(input.IndexOf('/') + 1);