How to remove characters in a string? - c#

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;
}

Related

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(#"\"));

read file name and find particular string

I have filename like
ChrysanthemumThumbnail82b09296a7c34373833050d362745a30.jpg
How can I find this string ChrysanthemumThumbnail
You can use Path.GetFileNameWithoutExtension method to read the file name without extension and then you can use string.Contains to check if it contains your string.
string fileName = Path.GetFileNameWithoutExtension("ChrysanthemumThumbnail82b09296a7c34373833050d362745a30.jpg");
if(fileName.Contains("ChrysanthemumThumbnail"))
{
//name found
}
if you want to see if the fileName starts with your string then you can use string.StartsWith
if(fileName.StartsWith("ChrysanthemumThumbnail"))
{
//file name starts with ChrysanthemumThumbnail
}
(if you have the FileName already in a string then you don't need Path.GetFileNameWithoutExtension it is only useful if you are trying to extract the filename from a path)
Did you want something like:
string filename = "ChrysanthemumThumbnail82b09296a7c34373833050d362745a30.jpg"
bool result = filename.Contains("ChrysanthemumThumbnail");
if the ChrysanthemumThumbnail always at start of the filename then just use 'StartWith'
, this will have better over contains which checks whole string
"ChrysanthemumThumbnail82b09296a7c34373833050d362745a30.jpg".StartsWith("ChrysanthemumThumbnail")
and if it can be at any location than use contains as suggested by Habib above
"ChrysanthemumThumbnail82b09296a7c34373833050d362745a30.jpg".Contains ("ChrysanthemumThumbnail")

How to split string based on another string

I have a string:
string fileName = VAH007157100_REINSTMT_20d5fe49.tiff
I want to split this at the end of REINSTMT.
string splittedFileName = fileName.split("REINSTMT")[0];
The above does not work.
How would I go about splitting it to grab everything from the left side of the word "REINSTMT"?
Try this
string splittedFileName = fileName.Split(new string[]{"REINSTMT"},
StringSplitOptions.None)[0];
In order to split based on a string rather than a char, you need to provide a second argument. See the documentation here.
What you probably want is
string splittedFileName = fileName.split(new string[] {"REINSTMT"}, StringSplitOptions.None)[0];
Another way would be with substring:
string fileName = "VAH007157100_REINSTMT_20d5fe49.tiff";
string splittedFileName = fileName.Substring(0, fileName.IndexOf("REINSTMT"));

How to get the relative filename to a specific directory?

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, "");

Get folder name from full file path

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.

Categories

Resources