I have two different Paths:
C:\Project\v4.0\Tool\Custom\CustomCompanyNames\Template\file\file.xml
C:\Destination\New\Place\Bin\Debug\output
I need a way two get values from two different paths
Expected Path:
C:\Destination\New\Place\Bin\Debug\output\CustomCompanyNames\file\file.xml
How can i solve it ?
Custom is a fix folder
All directories after Customs have different names
My Solution bad programmed:
Custom ist the first path
Destination the second path
private void test()
{
string result = destination;
string[] custom = customs.Split('\\');
foreach (var s in custom)
{
if(s.Contains("custom") || result.Contains("custom"))
{
if(s.Contains("templates")) break;
result = Path.Combine(result, s);
}
}
}
Instead of Splitting the path use IndexOf to find the Custom part and then Substring from it.
string path1 = #"C:\Project\v4.0\Tool\Custom\CustomCompanyNames\Template\file\file.xml";
string path2 = #"C:\Destination\New\Place\Bin\Debug\output";
string splitter = #"Custom\";
string desiredSection = path1.Substring(path1.IndexOf(splitter) + splitter.Length);
string output = Path.Combine(path2, desiredSection);
Related
I have the following string
string a = #"\\server\MainDirectory\SubDirectoryA\SubdirectoryB\SubdirectoryC\Test.jpg";
I'm trying to remove part of the string so in the end I want to be left with
string a = #"\\server\MainDirectory\SubDirectoryA\SubdirectoryB";
So currently I'm doing
string b = a.Remove(a.LastIndexOf('\\'));
string c = b.Remove(b.LastIndexOf('\\'));
Console.WriteLine(c);
which gives me the correct result. I was wondering if there is a better way of doing this? because I'm having to do this in a fair few places.
Note: the SubdirectoryC length will be unknown. As it is made of the numbers/letters a user inputs
There is Path.GetDirectoryName
string a = #"\\server\MainDirectory\SubDirectoryA\SubdirectoryB\SubdirectoryC\Test.jpg";
string b = Path.GetDirectoryName(Path.GetDirectoryName(a));
As explained in MSDN it works also if you pass a directory
....passing the returned path back into the GetDirectoryName method will
result in the truncation of one folder level per subsequent call on
the result string
Of course this is safe if you have at least two directories level
Heyho,
if you just want to get rid of the last part.
You can use :
var parentDirectory = Directory.GetParent(Path.GetDirectoryName(path));
https://msdn.microsoft.com/de-de/library/system.io.directory.getparent(v=vs.110).aspx
An alternative answer using Linq:
var b = string.Join("\\", a.Split(new string[] { "\\" }, StringSplitOptions.None)
.Reverse().Skip(2).Reverse());
Some alternatives
string a = #"\\server\MainDirectory\SubDirectoryA\SubdirectoryB\SubdirectoryC\Test.jpg";
var b = Path.GetFullPath(a + #"\..\..");
var c = a.Remove(a.LastIndexOf('\\', a.LastIndexOf('\\') - 1));
but I do find this kind of string extensions generally usefull:
static string beforeLast(this string str, string delimiter)
{
int i = str.LastIndexOf(delimiter);
if (i < 0) return str;
return str.Remove(i);
}
For such repeated tasks, a good solution is often to write an extension method, e.g.
public static class Extensions
{
public static string ChopPath(this string path)
{
// chopping code here
}
}
Which you then can use anywhere you need it:
var chopped = a.ChopPath();
i am assigning images[] with an array that holds images file names with full path of given Directory.
string[] images = DirLoad.FileNamesArray(
IO.Loaders.PathType.full,
IO.Loaders.FileExtension.jpg
);
...now, that images[] stores all the file names i need, as I had to use the full path to get it done,
using Directory.GetFiles()
Next action requires it as a local file name.
(each is then passed as string type parameter to another method)
so my question is :
How can i omit first part - HttpRuntime.AppDomainAppPath ...if it's same in every element of array ?
this is usage example, the string is currentDir i need to trim from each element in images[]
public class IO
{
public class Loaders
{
readonly string currentDir = HttpRuntime.AppDomainAppPath;
public string selecedDirName { get; set; }
/// <summary>
/// assign The Loaders.selectedDir First before calling
/// </summary>
/// <param name="foldertoLoad"></param>
/// <returns></returns>
public enum PathType
{
full, local
}
public enum FileExtension
{
jpg,png,txt,xml,htm,js,aspx,css
}
public string[] FileNamesArray(PathType SelectedPathMode, FileExtension selectedfileType)
{
string thisFolder = "";
string thatFileType= string.Format("*.{0}",selectedfileType.ToString());
switch (SelectedPathMode)
{
case PathType.full:
thisFolder = Path.Combine(currentDir, selecedDirName);
break;
case PathType.local:
thisFolder = selecedDirName;
break;
default:
break;
}
string[] foundArr = Directory.GetFiles(thisFolder, thatFileType);
return foundArr;
}
}
}
Update , this is what i've tried
string fileName;
string[] images = DirLoad.FilesArray(IO.Loaders.PathType.full, IO.Loaders.FileExtention.jpg);
foreach (var currImage in images)
{
int startingAt = DirLoad.currentDir.Length ;
int finalPoint = currImage.Length - startingAt;
fileName = new String(currImage.ToCharArray(startingAt, finalPoint));
baseStyle.Add(string.Format("{0}url({1}) {2}", BackGroundCssProp, fileName, imageProps));
}
return baseStyle.ToArray();
Still I fail to understand, what you're trying to accomplish from the beginning to the end, but..If you are having an array of full paths and you need to get only filenames from these paths, you can do the following:
Actually files may contain random, absolutely different paths, but according to what I have caught from the question, et it be:
var files = Directory.GetFiles(#"path");
Then you may use Path.GetFileName Method to retrieve only filename from these paths, through a simple Enumerable.Select LINQ-statement:
var fileNamesOnly = files.Select(f => Path.GetFileName(f));
I am not entirely sure what you exactly need. For your sentence:
the string is currentDir i need to trim from each element in images[]
You can try the following using LINQ:
string currDir = "SomeString";
string[] images = new string[] { "SomeStringabc1.jpg", "SomeStringabc2.jpg", "SomeStringabc3.jpg", "abc.jpg" };
string[] newImages = images.Select(r => r.StartsWith(currDir)
? r.Replace(currDir, "") : r)
.ToArray();
Or using string.TrimStart
string[] newImages = images.Select(r => r.TrimStart(currDir.ToCharArray())).ToArray();
sorry but it is not clear to me... if you want only the filename from whole path then you can simply use Split for it, split the whole path with special character and use last array element.
once you will get all the path in your "images" array you can try below code.
for example:-
for(i=0;i<images.length;i++)
{
string [] cuttofilename=images[i].split('\');
string filename=cuttofilename[cuttofilename.lentgh-1];
}
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
I am writing a C# program which reads certain tags from files and based on tag values it creates a directory structure.
Now there could be anything in those tags,
If the tag name is not suitable for a directory name I have to prepare it to make it suitable by replacing those characters with anything suitable. So that directory creation does not fail.
I was using following code but I realised this is not enough..
path = path.replace("/","-");
path = path.replace("\\","-");
please advise what's the best way to do it..
thanks,
Import System.IO namespace and for path use
Path.GetInvalidPathChars
and for filename use
Path.GetInvalidFileNameChars
For Eg
string filename = "salmnas dlajhdla kjha;dmas'lkasn";
foreach (char c in Path.GetInvalidFileNameChars())
filename = filename.Replace(System.Char.ToString(c), "");
foreach (char c in Path.GetInvalidPathChars())
filename = filename.Replace(System.Char.ToString(c), "");
Then u can use Path.Combine to add tags to create a path
string mypath = Path.Combine(#"C:\", "First_Tag", "Second_Tag");
//return C:\First_Tag\Second_Tag
You can use the full list of invalid characters here to handle the replacement as desired. These are available directly via the Path.GetInvalidFileNameChars and Path.GetInvalidPathChars methods.
The characters you must now use are: ? < > | : \ / * "
string PathFix(string path)
{
List<string> _forbiddenChars = new List<string>();
_forbiddenChars.Add("?");
_forbiddenChars.Add("<");
_forbiddenChars.Add(">");
_forbiddenChars.Add(":");
_forbiddenChars.Add("|");
_forbiddenChars.Add("\\");
_forbiddenChars.Add("/");
_forbiddenChars.Add("*");
_forbiddenChars.Add("\"");
for (int i = 0; i < _forbiddenChars.Count; i++)
{
path = path.Replace(_forbiddenChars[i], "");
}
return path;
}
Tip: You can't include double-quote ("), but you can include 2 quotes ('').
In this case:
string PathFix(string path)
{
List<string> _forbiddenChars = new List<string>();
_forbiddenChars.Add("?");
_forbiddenChars.Add("<");
_forbiddenChars.Add(">");
_forbiddenChars.Add(":");
_forbiddenChars.Add("|");
_forbiddenChars.Add("\\");
_forbiddenChars.Add("/");
_forbiddenChars.Add("*");
//_forbiddenChars.Add("\""); Do not delete the double-quote character, so we could replace it with 2 quotes (before the return).
for (int i = 0; i < _forbiddenChars.Count; i++)
{
path = path.Replace(_forbiddenChars[i], "");
}
path = path.Replace("\"", "''"); //Replacement here
return path;
}
You'll of course use only one of those (or combine them to one function with a bool parameter for replacing the quote, if needed)
The correct answer of Nikhil Agrawal has some syntax errors.
Just for the reference, here is a compiling version:
public static string MakeValidFolderNameSimple(string folderName)
{
if (string.IsNullOrEmpty(folderName)) return folderName;
foreach (var c in System.IO.Path.GetInvalidFileNameChars())
folderName = folderName.Replace(c.ToString(), string.Empty);
foreach (var c in System.IO.Path.GetInvalidPathChars())
folderName = folderName.Replace(c.ToString(), string.Empty);
return folderName;
}
I need to parse a directory string I get and remove last few folders.
For example, when I have this directory string:
C:\workspace\AccurevTestStream\ComponentB\include
I may need to cut the last two directores to create a new directory string:
C:\workspace\AccurevTestStream
what is a good way to do this? I know I can use string split and join but I think there may be a better way to do this.
var path = "C:\workspace\AccurevTestStream\ComponentB\include";
DirectoryInfo d = new DirectoryInfo(path);
var result = d.Parent.Parent.FullName;
Here's a simple recursive method that assumes you know how many parent directories to remove from the path:
public string GetParentDirectory(string path, int parentCount) {
if(string.IsNullOrEmpty(path) || parentCount < 1)
return path;
string parent = System.IO.Path.GetDirectoryName(path);
if(--parentCount > 0)
return GetParentDirectory(parent, parentCount);
return parent;
}
You could use the System.IO.Path class in this case - if you call Path.GetDirectoryName repeatedly, it will chop off the last path:
string path = #"C:\workspace\AccurevTestStream\ComponentB\include";
path = Path.GetDirectoryName(path); //returns C:\workspace\AccurevTestStream\ComponentB
path = Path.GetDirectoryName(path); //returns C:\workspace\AccurevTestStream
//etc
You might try:
myNewString = myOriginalString.SubString(0, LastIndexOf(#"\"));
myNewString = myNewString.SubString(0, LastIndexOf(#"\"));
Not elegant, but should be effective.
Edit: (even more inelegant)
string myNewString = myOriginalString;
for(i=0;i<NumberToChop;i++)
{
if(LastIndexOf(#"\") > 0)
myNewString = myNewString.SubString(0, LastIndexOf(#"\"));
}
I'd go with the DirectoryInfo class and its Parent property.
http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx
static String GoUp(String path, Int32 num)
{
if (num-- > 0)
{
return GoUp(Directory.GetParent(path).ToString(), num);
}
return path;
}
The easiest way to do this:
string path = #"C:\workspace\AccurevTestStream\ComponentB\include"
string newPath = Path.GetFullPath(Path.Combine(path, #"..\..\"));
Note This goes two levels up. The result would be:
newPath = #"C:\workspace\AccurevTestStream\";
What about this (sorry, I don't know what your criteria is for determining what to delete)...
var di = new System.IO.DirectoryInfo("C:\workspace\AccurevTestStream\ComponentB\include");
while (!deleteDir)
di = di.Parent;
di.Delete(true);