How can I split a string to obtain a filename? - c#

I am trying to split the string. Here is the string.
string fileName = "description/ask_question_file_10.htm"
I have to remove "description/" and ".htm" from this string. So the result I am looking for "ask_question_file_10". I have to look for "/" and ".htm" I appreciate any help.

You can use the Path.GetFileNameWithoutExtension Method:
string fileName = "description/ask_question_file_10.htm";
string result = Path.GetFileNameWithoutExtension(fileName);
// result == "ask_question_file_10"

string fileName = Path.GetFileNameWithoutExtension("description/ask_question_file_10.htm")

try
string myResult = fileName.SubString (fileName.IndexOf ("/") + 1);
if ( myResult.EndsWith (".htm" ) )
myResult = myResult.SubString (0, myResult.Length - 4);
IF it is really a path then you can use
string myResult = Path.GetFileNameWithoutExtension(fileName);
EDIT - relevant links:
http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension.aspx
http://msdn.microsoft.com/en-us/library/hxthx5h6.aspx
http://msdn.microsoft.com/en-us/library/2333wewz.aspx
http://msdn.microsoft.com/en-us/library/system.string.length.aspx

string fileName = "description/ask_question_file_10.htm";
string name = Path.GetFileNameWithoutExtension(fileName);

Related

Dealing with multiple '.' in a file extension

I have this string that contains a filename
string filename = "C:\\Users\\me\\Desktop\\filename.This.Is.An.Extension"
I tried using the conventional
string modifiedFileName = System.IO.Path.GetFileNameWithoutExtension(filename);
but it only gets me:
modifiedFileName = "C:\\Users\\me\\Desktop\\filename.This.Is.An"
In order for me to get "C:\\Users\\me\\Desktop\\filename" I would have to use System.IO.Path.GetFileNameWithoutExtension several times, and that's just not efficient.
What better way is there to take my file name and have it return the directory + filename and no exceptions?
Many thanks in advance!
If you want to stop at the first period, you will have to handle it yourself.
Path.GetDirectoryName(filepath) + Path.GetFileName(filepath).UpTo(".")
using this string extension:
public static string UpTo(this string s, string stopper) => s.Substring(0, Math.Max(0, s.IndexOf(stopper)));
Take the directory and the base name:
var directoryPath = Path.GetDirectoryName(filename);
var baseName = Path.GetFileName(filename);
Strip the base name’s “extensions”:
var baseNameWithoutExtensions = baseName.Split(new[] {'.'}, 2)[0];
Recombine them:
var modifiedFileName = Path.Combine(directoryPath, baseNameWithoutExtensions);
demo
Without built in function:
public static void Main(string[] args)
{
string s = "C:\\Users\\me\\Desktop\\filename.This.Is.An.Extension";
string newString="";
for(int i=0;i<s.Length;i++)
{
if(s[i]=='.'){
break;
}else{
newString += s[i].ToString();
}
}
Console.WriteLine(newString); //writes "C:\Users\me\Desktop\filename"
}

C# Filter differences from a path

DirectoryPath = C:\Pics
filePath = C:\Pics\Dogs\dog.PNG
newPath should be: Dogs\dog.PNG
How do I get the newPath?
My code snippet is not right
string directoryPath = "C:\\Pics";
string filePath = "C:\\Pics\\Dogs\\dog.PNG";
if (!directoryPath.EndsWith("\\"))
directoryPath = directoryPath + "\\";
string newPath = filePath.Substring(filePath.LastIndexOf(directoryPath) + 1);
Thanks in advance!
Could you append a backslash to the directory path & then in the filepath replace the directory path with an empty string
newPath = filePath.Replace(DirectoryPath + #"\", string.Empty);
If the directoryPath does not match the start of the filePath, then newPath will be unchanged.
I did post this before you edited your code to show the conditional adding of the backslash - so that can be removed in the above code.
The int Index you get from LastIndexOf() will always starts with the rightmost value, in your case 0. You have also to add the String.Lenght for this.
if (filePath.StartsWith(directoryPath))
{
string newPath =
filePath.Substring(filePath.LastIndexOf(directoryPath) + directoryPath.Length + 1);
}
I would first check if filePath contains DirectoryPath,so i'd do something like this:
var newPath=filePath.Contains(DirectoryPath)?filePath.Substring(DirectoryPath.Length + 1)
:filePath;
Or even better,using StartsWith
var newPath=filePath.StartsWith(DirectoryPath)?filePath.Substring(DirectoryPath.Length + 1)
:filePath;

How to Remove number from Extension with string?

I want to remove number from Extension with string in C#.
For Example : "Url1234.pdf" I want the last answer looks like "Url.pdf"
Thank you for your Contribution
var fileName = "";
if (file != null && file.ContentLength > 0)
{
fileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName); //Path.GetFileName(file.FileName);
var extension = System.IO.Path.GetExtension(file.FileName);
DBConnect.OpenDB();
DBConnect.DbSelect("select MAX(ID) as ID from tblFileUpload");
if(DBConnect.dr.Read())
{
fileName += DBConnect.dr["ID"].ToString();
}
DBConnect.CloseDB();
var path = Path.Combine(Server.MapPath("~/File/"), fileName+extension);
new FileUploadLayer().save("aa", fileName, file.ContentLength);
file.SaveAs(path);
UploadFile("aa");
}
I save a file with the extension(.pdf). That file name has numbers also.(Url1234.pdf).So, when i call it back i need to remove those numbers and only need the string part (Url.pdf).
You can use regex as shown or a simple LINQ query, i'd also recommend System.IO.Path:
string originalPath = "Url1234.pdf";
string dir = Path.GetDirectoryName(originalPath); // in this case ""
string extension = Path.GetExtension(originalPath); // .pdf
string fn = Path.GetFileNameWithoutExtension(originalPath); // Url1234
string newFn = String.Concat(fn.Where(c => !Char.IsDigit(c))); // Url
string newPath = Path.Combine(dir, newFn + extension); // Url.pdf
You can use Regex to replace numbers with empty string:
var result1 = Regex.Replace("Url1234.pdf", #"[\d-]", string.Empty);
Add using System.Text.RegularExpressions;

HttpContext.Current.Request.Url How to get the part after application name from URL

var myPath = HttpContext.Current.Request.Url.AbsolutePath;
// output: myApplication/myFolder/myPage.aspx
var pageName = Path.GetFileName(myPath);
//output: myPage.aspx
I am trying to output "myFolder/myPage.aspx" without the application path.
Is there built-in option to return that or I would need to use regular expression to get what I need?
Thanks
You should be able to make use of HttpContext.Current.Request.Url.Segments and then a simple string concat:
String[] segments = HttpContext.Current.Request.Url.Segments;
string result = segments[1] + segments[2];
or instead of string concat, use: string result = Path.Combine(segments[1],segments[2]);
This should work
public ActionResult oihoi(string ImageName
{
string _FileName = Path.GetFileName(ImageName.FileName);
string folderpath = "UploadedFiles/WebGallery";
string path = Server.MapPath("~/" + folderpath);
string firstsegment = "";
}

Remove the last character if it's DirectorySeparatorChar with C#

I need to extract the path info using Path.GetFileName(), and this function doesn't work when the last character of the input string is DirectorySeparatorChar('/' or '\').
I came up with this code, but it's too lengthy. Is there a better way to go?
string lastCharString = fullPath.Substring (fullPath.Length-1);
char lastChar = lastCharString[0];
if (lastChar == Path.DirectorySeparatorChar) {
fullPath = fullPath.Substring(0, fullPath.Length-1);
}
fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar);
// If the fullPath is not a root directory
if (Path.GetDirectoryName(fullPath) != null)
fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
while(fullPath.EndsWith(Path.DirectorySeparatorChar.ToString())){
fullPath = fullPath.Substring(0, fullPath.Length-1);
}
string path1 = #"c:\directory\";
string path2 = #"c:\directory\file.txt";
string path3 = #"c:\directory";
Console.WriteLine(Path.Combine(Path.GetDirectoryName(path1), Path.GetFileName(path1)));
Console.WriteLine(Path.Combine(Path.GetDirectoryName(path2), Path.GetFileName(path2)));
Console.WriteLine(Path.Combine(Path.GetDirectoryName(path3), Path.GetFileName(path3)));
Gives:
c:\directory
c:\directory\file.txt
c:\directory
Hope it helps.
fullPath = Path.GetFileName(
fullPath.Split(
new [] { Path.DirectorySeparatorChar },
StringSplitOptions.RemoveEmptyEntries
).Last()
)
Based on Marino Šimić's answer and Dima's comment here is a solution which will not fail on C: and C:\:
var newPath = Path.Combine(Path.GetDirectoryName(oldPath) ?? oldPath, Path.GetFileName(oldPath));

Categories