Basically I want to sub-string directory path for example path is "server/student/personal/contact"
I want to path like "/student/personal/contact". That's mean first folder name I don't want to in
in path. Every time this path is change by project requirement so how to remove first folder name
from string path.
problem that here in string path first Folder name not same name every time So please help for this how to remove first folder name from string path
Try this:
string strp = "server/student/personal/contact";
strp = strp.Substring(strp.IndexOf("/"));
Output:
/student/personal/contact
I usually write something like this
string example = "server/student/personal/contact";
var paths = example.Split('/').ToList();
if (paths.Any())
{
paths.RemoveAt(0);
}
string result = string.Join("/", paths);
or you can:
string example = "server/student/personal/contact";
var pos = example.IndexOf("/", System.StringComparison.Ordinal);
if (pos > 0)
{
example = example.Substring(pos);
}
you can simply do this :
string path = "server/student/personal/contact";
//IndexOf() gives you the first occurrence of the character.
int firstSlash=path.IndexOf('/');
string modifiedPath = path.Substring(firstSlash);
Related
I need to get a folder path some file that has the different name on every computer. For which I need to scan the folder that contain this file with randomly generated name and then store the name of that folder as a string so that I can add to the path.
Here is my code:
string mypath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string mypath1 = #"\Roaming\Mozilla\Firefox\Profiles\";
string mypath2 = //here is where i would like to scan the \Roaming\Mozilla\Firefox\Profiles\ and store the folder inside as a string
string all_path = mypath + mypath1 + mypath2;
I believe the example at https://msdn.microsoft.com/en-us/library/c1sez4sc(v=vs.110).aspx will show you how to do what you want, it includes parsing and navigating subdirecties, including getting the name of them like you want.
Specifically the line:
string [] directories = Directory.GetDirectories(mpath1 + mypath2)
I want to cut out a part of a path but don't know how.
To get the path, I use this code:
String path = System.IO.Path.GetDirectoryName(fullyQualifiedName);
(path = "Y:\Test\Project\bin\Debug")
Now I need the first part without "\bin\Debug".
How can I cut this part out of the current path?
If you know, that you don't need only "\bin\Debug" you could use replace:
path = path.Replace("\bin\Debug", "");
or
path = path.Remove(path.IndexOf("\bin\Debug"));
If you know, that you don't need everything, after second \ you could use this:
path = path.Remove(path.LastIndexOfAny(new char[] { '\\' }, path.LastIndexOf('\\') - 1));
and finally, you could Take so many parts, how many you want like this:
path = String.Join(#"\", path.Split('\\').Take(3));
or Skip so many parts, how many you need:
path = String.Join(#"\", path.Split('\\').Reverse().Skip(2).Reverse());
You can use the Path class and a subsequent call of the Directory.GetParent method:
String dir = Path.GetDirectoryName(fullyQualifiedName);
string root = Directory.GetParent(dir).FullName;
You can do it within only 3 lines.
String path= #"Y:\\Test\\Project\\bin\\Debug";
String[] extract = Regex.Split(path,"bin"); //split it in bin
String main = extract[0].TrimEnd('\\'); //extract[0] is Y:\\Test\\Project\\ ,so exclude \\ here
Console.WriteLine("Main Path: "+main);//get main path
You can obtain the path of the parent folder of your path like this:
path = Directory.GetParent(path);
In your case, you'd have to do it twice.
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 probably didn't word the title too well but hopefully my explanation should illustrate the problem.
Basically, I have to find out the names of the subdirectories excluding the file name when given another path to compare with. For instance,
Given: "C:\Windows\System32\catroot\sys.dll"
Compare: "C:\Windows"
Matched String: "\System32\catroot"
Here's another example:
Given: "C:\Windows\System32\WindowsPowerShell\v1.0\Examples\profile.ps1"
Compare: "C:\Windows\System32"
Matched String: "\WindowsPowerShell\v1.0\Examples"
What would be the best way to perform this matching?
You might also want to consider special cases such as:
Relative paths
Paths with short names such as C:\PROGRA~1 for C:\Program Files
Non-canonical paths (C:\Windows\System32\..\..\file.dat)
Paths that use an alternate separator (/ instead of \)
One way is to convert to a canonical full path using Path.GetFullPath before comparing
E.g.
string toMatch = #"C:\PROGRA~1/";
string path1 = #"C:/Program Files\Common Files\..\file.dat";
string path2 = #"C:\Program Files\Common Files\..\..\file.dat";
string toMatchFullPath = Path.GetFullPath(toMatch);
string fullPath1 = Path.GetFullPath(path1);
string fullPath2 = Path.GetFullPath(path2);
// fullPath1 = C:\Program Files\file.dat
// toMatchFullPath = C:\Program Files\
if (fullPath1.StartsWith(toMatchFullPath, StringComparison.OrdinalIgnoreCase))
{
// path1 matches after conversion to full path
}
// fullPath2 = C:\file.dat
// toMatchFullPath = C:\Program Files\
if (fullPath2.StartsWith(toMatchFullPath, StringComparison.OrdinalIgnoreCase))
{
// path2 does not match after conversion to full path
}
There is no need to use Regex.
This could be easily done using string.StartsWith, string.Substring and Path.GetDirectoryName to remove the filename.
string fullPath = #"C:\Windows\System32\WindowsPowerShell\v1.0\Examples\profile.ps1";
string toMatch = #"C:\Windows\System32";
string result = string.Empty;
if(fullPath.StartsWith(toMatch, StringComparison.CurrentCultureIgnoreCase) == true)
{
result = Path.GetDirectoryName(fullPath.Substring(toMatch.Length));
}
Console.WriteLine(result);
EDIT: this changes take care of the observation from aiodintsov and include the idea from #Joe about non-canonical or partial path names
string fullPath = #"C:\Windows\System32\WindowsPowerShell\v1.0\Examples\profile.ps1";
string toMatch = #"C:\Win";
string result = string.Empty;
string temp = Path.GetDirectoryName(Path.GetFullPath(fullPath));
string[] p1 = temp.Split('\\');
string[] p2 = Path.GetFullPath(toMatch).Split('\\');
for(int x = 0; x < p1.Length; x++)
{
if(x >= p2.Length || p1[x] != p2[x])
result = string.Concat(result, "\\", p1[x]);
}
In this case I assume that the partial match should be considered as no match.
Also take a look at the answer from #Joe for the problem of partial or non-canonical paths
How do I get the folder name from the full path of the application?
This is the file path below,
c:\projects\root\wsdlproj\devlop\beta2\text
Here "text" is the folder name.
How can I get that folder name from this path?
See DirectoryInfo.Name:
string dirName = new DirectoryInfo(#"c:\projects\roott\wsdlproj\devlop\beta2\text").Name;
I think you want to get parent folder name from file path. It is easy to get.
One way is to create a FileInfo type object and use its Directory property.
Example:
FileInfo fInfo = new FileInfo("c:\projects\roott\wsdlproj\devlop\beta2\text\abc.txt");
String dirName = fInfo.Directory.Name;
Try this
var myFolderName = #"c:\projects\roott\wsdlproj\devlop\beta2\text";
var result = Path.GetFileName(myFolderName);
You could use this:
string path = #"c:\projects\roott\wsdlproj\devlop\beta2\text";
string lastDirectory = path.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).Last();
Simply use Path.GetFileName
Here - Extract folder name from the full path of a folder:
string folderName = Path.GetFileName(#"c:\projects\root\wsdlproj\devlop\beta2\text");//Return "text"
Here is some extra - Extract folder name from the full path of a file:
string folderName = Path.GetFileName(Path.GetDirectoryName(#"c:\projects\root\wsdlproj\devlop\beta2\text\GTA.exe"));//Return "text"
I figured there's no way except going into the file system to find out if text.txt is a directory or just a file. If you wanted something simple, maybe you can just use:
s.Substring(s.LastIndexOf(#"\"));
In this case the file which you want to get is stored in the strpath variable:
string strPath = Server.MapPath(Request.ApplicationPath) + "/contents/member/" + strFileName;
Here is an alternative method that worked for me without having to create a DirectoryInfo object. The key point is that GetFileName() works when there is no trailing slash in the path.
var name = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar));
Example:
var list = Directory.EnumerateDirectories(path, "*")
.Select(p => new
{
id = "id_" + p.GetHashCode().ToString("x"),
text = Path.GetFileName(p.TrimEnd(Path.DirectorySeparatorChar)),
icon = "fa fa-folder",
children = true
})
.Distinct()
.OrderBy(p => p.text);
This can also be done like so;
var directoryName = System.IO.Path.GetFileName(#"c:\projects\roott\wsdlproj\devlop\beta2\text");
Based on previous answers (but fixed)
using static System.IO.Path;
var dir = GetFileName(path?.TrimEnd(DirectorySeparatorChar, AltDirectorySeparatorChar));
Explanation of GetFileName from .NET source:
Returns the name and extension parts of the given path. The resulting
string contains the characters of path that follow the last
backslash ("\"), slash ("/"), or colon (":") character in
path. The resulting string is the entire path if path
contains no backslash after removing trailing slashes, slash, or colon characters. The resulting
string is null if path is null.