Getting part of the filename C# - c#

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;

Related

C# cut file Name from Path

I am creating an Image Extraction tool and I am able to retrieve the Images with full path..
For Example:
I need to cut the File name (rss) from path...
I search posts and Tried following
//1.
//string str = s.Split('/', '.')[1];
//2.
string s1;
// string fileName = "abc.123.txt";
int fileExtPos = s.LastIndexOf(".");
if (fileExtPos >= 0)
s1 = s.Substring(0, fileExtPos);
//3.
//var filenames = String.Join(
// ", ",
// Directory.GetFiles(#"c:\", "*.txt")
// .Select(filename =>
//4.
// Path.GetFileNameWithoutExtension(filename)));
None seems to be working
I want the name between "images" and "png" ..What can be the exact code?
Any Suggestion will be helpful
Just use the class Path and its method GetFileNameWithoutExtension
string file = Path.GetFileNameWithoutExtension(s);
Warning: In this context (just the filename without extension and no arguments passed after the URL) the method works well, however this is not the case if you use other methods of the class like GetDirectoryName. In that context the slashes are reversed into Windows-style backslashes "\" and this could be an error for other parts of your program
Another solution, probably more WEB oriented is through the class Uri
Uri u = new Uri(s);
string file = u.Segments.Last().Split('.')[0];
but I find this a lot less intuitive and more error prone.
In your example you're using a uri so you should use System.Uri
System.Uri uri = new System.Uri(s);
string path = uri.AbsolutePath;
string pathWithoutFilename = System.IO.Path.GetDirectoryName(path);
Why use Uri? Because it will handle things like
http://foo.com/bar/file.png#notthis.png
http://foo.com/bar/file.png?key=notthis.png
http://foo.com/bar/file.png#moo/notthis.png
http://foo.com/bar/file.png?key=moo/notthis.png
http://foo.com/bar/file%2epng
Etc.
Here's a fiddle
You should use the various System.IO.Path functions to manipulate paths as they work cross platform. Similarly you should use the System.Uri class to manipulate Uris as it will handle all the various kinds of edge cases like escaped characters, fragments, query strings, etc.

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 can I replace the same name of a file using regex but in another format?

I am new in programming and not so good about regex. I wish to load / read a csv File and then save in a txt File using the same name of csv File. I will give an example.
D:\Project\File\xxx.csv
After I load this file, I want to get the name "xxx" and save it in a txt file:
D:\Project\File\xxx.txt
Or maybe in another folder, for example:
D:\Project\Specifications\PersonInfo.csv
save to
D:\Project\DataBank\PersonInfo.txt
This can be accomplished in many ways.
Maybe what you're lacking is knowledge of the System.IO.Path class (MSDN article here).
For instance changing the extension could be accomplished like so:
string originalFilePath = #"D:\Project\File\xxx.csv";
string newFilePath = Path.ChangeExtension(originalFilePath, ".txt");
Note: You need to explicitate the leading dot (".") for the extension.
Here's some "Path algebra" fun you could combine to create your desired effects:
string originalFilePath = #"D:\Project\File\xxx.csv";
string thePath = Path.GetDirectoryName(originalFilePath);
// will be #"D:\Project\File"
string filename = Path.GetFileName(originalFilePath);
// will be "xxx.csv"
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(originalFilePath);
// will be "xxx"
string recombinedFilePath = Path.Combine( #"D:\OtherFolder", "somethingElse.txt" );
// will be #"D:\OtherFolder\somethingElse.txt"
Note: Path.Combine knows how to handle extra/missing leading/trailing backslashes.
For example:
Path.Combine(#"D:\MyFolder1", #"MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1\", #"MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1", #"\MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1\", #"\MyFolder2\MyFile.txt")
will all yield the same result: #"D:\MyFolder1\MyFolder2\MyFile.txt"
You do not need regex for that, because .NET provides a System.IO.Path class for dealing specifically with file name manipulations.
For example, to replace .csv with .txt you can use this call:
var csvPath = #"D:\Project\File\xxx.csv";
var txtPath = Path.Combine(
Path.GetDirectoryName(csvPath)
, Path.GetFileNameWithoutExtension(csvPath)+".txt"
);
You use a similar trick to replace other parts of the file path. Here is how you change the name of the top directory:
var csvPath = #"D:\Project\Specifications\xxx.csv";
var txtPath = Path.Combine(
Path.GetDirectoryName(Path.GetDirectoryName(csvPath))
, "DataBank"
, Path.GetFileNameWithoutExtension(csvPath)+".txt"
);
You don't need Regex.
You can use Path.GetFileName or Path.GetFileNameWithoutExtension:
string fileName = Path.GetFileNameWithoutExtension("D:\Project\Specifications\PersonInfo.csv");
If you want to use regex for this, this regex will get the part you want:
([^\\]+)\.[^.\\]+$
The first group (in the parentheses) matches one or more characters (as many as possible) which is not a backslash. Then there need to be a literal dot. Then one or more characters (as many as possible) that are not a dot or backslash, then the end of the string. The group captures the wanted part.

How can we remove certain folder name from the path and return new path?

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 a certain substring in C#

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

Categories

Resources