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(#"\"));
Related
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]
I have a path:
"C:\\Users\\dev\\Test\\TestResults\\Config\\Report.xml"
I need to check if this path has folder "TestResults", if it has then I need to remove this and return new path as
"C:\\Users\\dev\\Test\\Config\\Report.xml"
I know I can achieve this using trim and split. But just to make sure I pick up a right choice. What is the best way of achieving this?
Any help really appriciated.
i would not use string replace method in this case. Why?
e.g. :
string path = "C:\\Users1\\Users2\\Users122\\Users13\\Users133\\filename.xml";
path = path.Replace("\\TestResults", string.Empty);
// you will get "C:\Users222333\filename.xml"
that is not what you expected.
so how to fix this,
path = string.Join(Path.DirectorySeparatorChar.ToString(),
path.Split(Path.DirectorySeparatorChar).Where(x=> x!="Users1").ToArray()));
//C:\Users2\Users122\Users13\Users133\filename.xml
You can use String.Replace method like;
Returns a new string in which all occurrences of a specified Unicode
character or String in the current string are replaced with another
specified Unicode character or String.
string path = "C:\\Users\\dev\\Test\\TestResults\\Config\\Report.xml";
path = path.Replace("\\TestResults", string.Empty);
Console.WriteLine(path);
Output will be;
C:\Users\dev\Test\Config\Report.xml
Here a DEMO.
How to remove the some characters in a string ..
string s="testpage\information.xml"
I need only information.xml how to do that?
System.IO.Path may help you with this since the string contains a file path information. In your case, you may use Path.GetFileName(string path) to get the file name from a string.
Example
string s = #"testpage\information.xml";
string filename = Path.GetFileName(s);
//MessageBox.Show(filename);
Thanks,
I hope you find this helpful :)
Assuming the value that will be in s is always a file path, use the Path class to extract the file name
var filename = Path.GetFileName(s);
File path is of the form
aaaa\bbb\ccc\dddd\information.xml
To retrieve the last string, you can divide your string using the delimiter \
String path = #"aaaa\bbb\ccc\dddd\information.xml";
String a[] = path.Split('\\');
This will give String array as ["aaaa", "bbb", "ccc", "dddd", "information.xml"]
You can retrieve the filename as
String filename = a[a.Length-1];
If it is going to be a file path, then you can use the System.IO.Path class (MSDN) to extract the filename.
string s = "testpage\information.xml"
var filename = Path.GetFilename(s);
If it's always right of the backslash separator then you can use:
if (s.Contains(#"\"))
s= s.Substring(s.IndexOf(#"\") + 1);
Hope this is what you want:
var result=s.Substring(s.LastIndexOf(#"\") + 1);
If you are using file paths, see the Path.GetFileName Method
It will not check whether the file exists or not. So it will be faster.
s = Path.GetFileName(s);
If you need to check whether file exists, use File.Exists class.
Another way is to use String.Split() method
string[] arr = s.Split('\\');
if(arr.Length > 0)
{
s = arr[arr.Length - 1];
}
Another way is to use RegEx
s = Regex.Match(s, #"[^\\]*$").Value;
You can use the following line of codes to get file extension.
string filePath = #"D:\Test\information.xml";
string extention = Path.GetExtension(filePath);
If you need file name alone use,
string filePath = #"D:\Test\information.xml";
string filename = Path.GetFilename(filePath );
Use string.Replcae
string s = #"testpage\information.xml";
s = s.Replace(#"testpage\\",""); // replace 'testpage\' with empty string
You will get Output => s=information.xml
# is need only because you have backslash in your string
For further reading about STRING REPLACE
http://www.dotnetperls.com/replace
http://msdn.microsoft.com/en-us/library/system.string.replace.aspx
In C++ you can do something like this. Basically search for "/" or "\" from right to left of the path and crop the string starting from the first occurance of the delimiter:
string ExtractFileName(const string& strPathFileName)
{
size_t npos;
string strOutput = strPathFileName;
if(strPathFileName.rfind(L'/', npos) || strPathFileName.rfind(L'\\', npos))
{
strOutput = strPathFileName.substr(npos+1);
}
return strOutput;
}
I have a method which is doing a file copy. The 'root' is specified by the user on the command line, which I sanitize with Path.GetFullPath(input).
I need to get the path of the file relative to that root, so the following cases would return:
Root FilePath Return
y:\ y:\temp\filename1.txt temp\filename1.txt
y:\dir1 y:\dir1\dir2\filename2.txt dir2\filename2.txt
You can write
var relative = new Uri(rootPath).MakeRelativeUri(new Uri(filePath));
http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx
string s1 = "y:\\";
string s2 = "y:\\temp\filename1.txt";
Console.WriteLine(s2.Substring(s1.Length)); \\ Outputs temp\filename1.txt
Hope this helps
Might want to call a .Trim() as well to ensure removing trailing \ characters or the like.
System.IO.Path.GetFullPath( filePath ).Substring( rootPath.Length )
string relativePath = Path.GetFullPath(input).Replace(rootPath, "");
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);