Related paths in c# - c#

I have this situation in c# application
have 2 paths in my windows
C:\Projectos\FrameworkCS\CSoft.Core
C:\Projectos2\CSoft.Core
and i need get related path of second related with first like this:
..\..\Projectos2\CSoft.Core
Exists a way to do this in c# or some one have a function can help me

Try MakeRelativeUri:
Uri first = new Uri(#"C:\Projectos2\CSoft.Core");
Uri second = new Uri(#"C:\Projectos\FrameworkCS\CSoft.Core ");
string relativePath = second.MakeRelativeUri(first).ToString();
Result:
"../../Projectos2/CSoft.Core"

I would probably figure it out by splitting both using the '\' as a separator. I would then count array items that were the same to get my common bond. Then I would build the destination path using the remaining items in the destination array and build the ..\ string by counting the remaining items in the source.
Common path = C:\Projectos\
Remaining destination path = CSoft.Core
Remaining source path has 1 more item (not including the file name itself) giving you ..\
Join the ..\ with the CSoft.Core giving you ..\CSoft.Core
Addendum: I didn't realise you could use the URI.MakeRelativePath() method for this - don't bother reinventing the wheel if it's already been done elsewhere.

Related

How to get some elements from array which contain some specific text and dont duplicate it?

I have an array of file paths and I want to create array that contains only uniqe files in paths_after array. Files is always starting at "OpenShop_".
Example: C:\aaa\OpenShop_F.dll; C:\aaa\vvv\OpenShop_F.dll; C:\aaa\OpenShop_E.dll
I have that code:
string[] paths = Directory.GetFiles(path, "OpenShop*.dll",SearchOption.AllDirectories);
string[] endpaths;
endpaths = paths.Where(x=>Path.GetFileName(x).Contains("OpenShop_")).Distinct().ToArray();
I want to in endpaths array elements with unique filenames: c:\aaa\OpenShop_F.dll
c:\aaa\OpenShop_E.dll
And I have result:
I dont want the same dll's. I want only one OpenShop_Firefox.dll only one Chrome and only one IE.
You could try something like the following:
var endpaths = paths.Where(x=>Path.GetFileName(x).Contains("open_"))
.Select(x=>Path.GetFileName(x))
.Distinct()
.ToArray();
We use the Path.GetFileName to get the filename from the path x. For further documentation about this, please have a look here. Then we see if the desired path is contained in the path we get. Last we get the distinct paths and convert the resutl to an array.

Get the last part of file name in C#

I need get last part means the numeric value(318, 319) of the following text (will vary)
C:\Uploads\X\X-1\37\Misc_318.pdf
C:\Uploads\X\X-1\37\Misc_ 319.pdf
C:\Uploads\X\C-1\37\Misc _ 320.pdf
Once I get that value I need to search for the entire folder. Once I find the files name with matching number, I need to remove all spaces and rename the file in that particular folder
Here is What I want
First get the last part of the file(numeric number may vary)
Based upon the number I get search in the folder to get all files names
Once I get the all files name check for spaces with file name and remove the spaces.
Finding the Number
If the naming follows the convention SOMEPATH\SomeText_[Optional spaces]999.pdf, try
var file = System.IO.Path.GetFileNameWithoutExtension(thePath);
string[] parts = file.split('_');
int number = int.Parse(parts[1]);
Of course, add error checking as appropriate. You may want to check that there are 2 parts after the split, and perhaps use int.TryParse() instead, depending on your confidence that the file names will follow that pattern and your ability to recover if TryParse() returns false.
Constructing the New File Name
I don't fully understand what you want to do once you have the number. However, have a look at Path.Combine() to build a new path if that's what you need, and you can use Directory.GetFiles() to search for a specific file name, or for files matching a pattern, in the desired directory.
Removing Spaces
If you have a file name with spaces in it, and you want all spaces removed, you can do
string newFilename = oldFilename.Replace(" ", "");
Here's a solution using a regex:
var s = #"C:\Uploads\X\X-1\37\Misc_ 319.pdf";
var match = Regex.Match(s, #"^.*?(\d+)(\.\w+)?$");
int i = int.Parse(match.Groups[1].Value);
// do something with i
It should work with or without an extension of any length (as long as it's a single extension, not like my file 123.tar.gz).

c# Search text files for specific string and get file path

Using c# in a Windows Form I need to search a directory "C:\XML\Outbound" for the file that contains an order number 3860457 and return the path to the file that contains the order number so I can then open the file and display the contents to the user in a RickTextBox.
The end user will have the order number but will not know what file contains that order number so that is why I need to search all files till it finds the filecontaining the order number and return the path (e.g. "C:\XML\Outbound\some_file_name_123.txt")
I am somewhat new to c# so I am not even sure where to start with this. Any direction for this?
Sorry the order number is inside the file so I need to search each file contents for the order number and once the file containing the order number is found return the path to that file. Order number is not part of the file name.
Straight answer:
public string GetFileName(string search){
List<string> paths = Directory.GetFiles(#"C:\XML\Outbond","*.txt",SearchOption.AllDirectories).ToList();
string path = paths.FirstOrDefault(p=>File.ReadAllLines(p).Any(line=>line.IndexOf(search)>=0));
return path;
}
Not-so straight answer:
Even though the above function will give you the path for given string (some handling of errors and edge cases may be nice) it will be terribly slow, especially if you have lots of files. If that's the case you need to tell us more about your environment because chances are you're doing it wrong (:

How to handle paths to files with extra parameters in C#?

I'm downloading files from the Internet inside of my application. Now I'm dealing with multiple file types so I need to able to detect what file type the file is before my application can continue. The problem that I ran into is that some of the URLs where the files are getting downloaded from contain extra parameters.
For example:
http://www.myfaketestsite.com/myaudio.mp3?id=20
Originally I was using String.EndsWith(). Obviously this doesn't work anymore. Any idea on how to detect the file type?
Wrap the URL in a Uri class. It will split it up into different segments that you can use, or you can use the helper methods on the Uri class itself:
var uri = new Uri("http://www.myfaketestsite.com/myaudio.mp3?id=20");
string path = uri.GetLeftPart(UriPartial.Path);
// path = "http://www.myfaketestsite.com/myaudio.mp3"
Your question is a duplicate of:
Truncating Query String & Returning Clean URL C# ASP.net
Get url without querystring
You could always split on the question mark to eliminate the parameters. e.g.
string s = "http://www.myfaketestsite.com/myaudio.mp3?id=20";
string withoutQueryString = s.Split('?')[0];
If no question mark exists, it won't matter, as you'll still be grabbing the value from the zero index. You can then do your logic on the withoutQueryString string.

Find a part of UNC path and put in a variable?

I am trying to peel off the last part of a unc path that is being passed and put it in a variable to use in a method further down the line.
Example path would be --> \\ourfileserver\remoteuploads\countyfoldername\personfoldername
How do I peel just the countyfoldername out of that?
I had thought to try
var th = e.FullPath.LastIndexOf('\\');
var whichFolder = folderPath.Substring(th);
but that is an escape character and it doesn't like # either.
Is this even the right direction?
I think I have confused some of you. LastIndexOf doesn't work because I need the countyfoldername which, in my example, occurs 3/4 of the way through.
Also, I need the countyfoldername stored in a variable, not the file name itself.
To give some context, I have a FileSystemWatcher that runs in a service. It was monitoring a single folder path and emailing when a file was created there. Now I need to modify it. There are now 4 county folders at that folder path and I need to send an email to a different email address depending on where a file is created.
I can use a simple switch statement if I can figure out how to get the county folder name reliably.
Thanks
Actually, you should use the Uri Class and break it into segments.
Uri uri = new Uri(#"\\ourfileserver\remoteuploads\countyfoldername\personfoldername");
Console.WriteLine(uri.Segments[3]); // personfoldername
Console.ReadLine();
string folder = System.IO.Path.GetFileName(fullpath)
Full docs here.
You need to create a substring from LastIndexOf("\")
Looks something like:
var folderName = e.FullPath.Substring(e.FullPath.LastIndexOf("\\"));
Did you try:
var myCounty = e.FullPath.LastIndexOf("\\");
Update:
In order to get the country folder name, just trim off the number of characters found from the county look up, then do another last index of..
I think you should split.
string[] Sep= {"\\"}
string[] Folders;
Folders= folderPath.Split(NewLine, StringSplitOptions.RemoveEmptyEntries);
You can traverse the array and hace full control over the string.

Categories

Resources