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));
Related
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;
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;
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 = "";
}
How can i get the root directory of a folder +1?
Example:
Input: C:\Level1\Level2\level3
output should be:
Level1
If input is Level1
output should be Level1
if input is C:\ output should be empty string
Is there is a .Net function handles this?
Directory.GetDirectoryRoot will always returns C:\
You can use the Path-class + Substring + Split to remove the root and get the top-folder.
// your directory:
string dir = #"C:\Level1\Level2\level3";
// C:\
string root = Path.GetPathRoot(dir);
// Level1\Level2\level3:
string pathWithoutRoot = dir.Substring(root.Length);
// Level1
string firstFolder = pathWithoutRoot.Split(Path.DirectorySeparatorChar).First();
Another way is using the DirectoryInfo class and it's Parent property:
DirectoryInfo directory = new DirectoryInfo(#"C:\Level1\Level2\level3");
string firstFolder = directory.Name;
while (directory.Parent != null && directory.Parent.Name != directory.Root.Name)
{
firstFolder = directory.Parent.Name;
directory = directory.Parent;
}
However, i would prefer the "lightweight" string methods.
string dir = #"C:\foo\bar\woah";
var dirSegments = dir.Split(new char[] { Path.DirectorySeparatorChar },
StringSplitOptions.RemoveEmptyEntries);
if (dirSegments.Length == 1)
{
return string.Empty;
}
else
{
return dirSegments[0] + Path.DirectorySeparatorChar + dirSegments[1];
}
You could loop up using the directory info class using the following structure by adding the code section below into a method
string path = "C:\Level1\Level2\level3";
DirectoryInfo d = new DirectoryInfo(path);
while (d.Parent.FullName != Path.GetPathRoot(path))
{
d = d.Parent;
}
return d.FullName;
You could use DirectoryInfo and a while loop.
DirectoryInfo info = new DirectoryInfo(path);
while (info.Parent != null && info.Parent.Parent != null)
info = info.Parent;
string result = info.FullName;
Not sure whether this is the correct way but you do:
string s = #"C:\Level1\Level2\Level3";
string foo = s.split(#"\")[1];
Not sure whether DirectoryInfo object can get this in a cleaner manner..
DirectoryInfo di = new DirectoryInfo(#"C:\Level1\Level2\Level3");
di.Root;
One possible solution, but may not be the best, is to find the position of #"\", and do some manual processing yourself. Below code is not fully tested, just snippet:
//var positions = inputString.IndexOfAny(new [] {'\'}); //Original one
//Updated, thanks to Snixtor's implementation
var positions = inputString.IndexOfAny(new [] {Path.DirectorySeparatorChar});
int n=positions.Length;
if(n>=1)
{
var pos = positions[1]; //The 2nd '\';
return inputString.SubString(0, pos);
}
return null;
Of course, this only works if we are sure we want chop substrings after the 2nd '\'.
A happy linq one liner:
string level1_2 = Directory.GetDirectoryRoot(path) + path.Split(Path.DirectorySeparatorChar).Skip(1).Take(1).DefaultIfEmpty("").First();
var di = new System.IO.DirectoryInfo(#"C:\a\b\c");
Func<DirectoryInfo, DirectoryInfo> root = null;
root = (info) => info.Parent.FullName.EndsWith("\\") ? info : root(info.Parent);
var rootName = root(di).Name; //#a
Why not just use System.IO.Path to retrieve the name?
MessageBox.Show(System.IO.Path.GetFileName(
System.IO.Path.GetDirectoryName(
System.IO.Path.GetDirectoryName(#"C:\Level1\Level2\Level3")
)
));
This returns Level 1.
MessageBox.Show(System.IO.Path.GetFileName(
System.IO.Path.GetDirectoryName(
System.IO.Path.GetDirectoryName(#"C:\")
)
));
This returns empty string.
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);