Find a part of UNC path and put in a variable? - c#

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.

Related

Use Path.GetFileNameWithoutExtension method in C# to get the file name but the display is not complete

This is the simple C# code I wrote :
string file = #"D:\test(2021/02/10).docx";
var fileName = Path.GetFileNameWithoutExtension(file);
Console.WriteLine(fileName);
I thought I would get the string "test(2021/02/10)" , but I got this result "10)".
How can I solve such a problem?
I just wonder why would you want such behavior. On windows slashes are treated as separator between directory and subdirectory (or file).
So, basically you are not able to create such file name.
And since slashes are treated as described, it is very natural that method implementation just checks what's after last slash and extracts just filename.
If you are interested on how the method is implemented take a look at source code

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

Parsing a string to extract a URL or folder path

I asked a similar question recently about using regex to retrieve a URL or folder path from a string. I was looking at this comment by Dour High Arch, where he says:
"I recommend you do not use regexes at all; use separate code paths
for URLs, using the Uri class, and file paths, using the FileInfo
class. These classes already handle parsing, matching, extracting
components, and so on."
I never really tried this, but now I am looking into it and can't figure out if what he said actually is useful to what I'm trying to accomplish.
I want to be able to parse a string message that could be something like:
"I placed the files on the server at http://www.thewebsite.com/NewStuff, they can also
be reached on your local network drives at J:\Downloads\NewStuff"
And extract out the two strings http://www.thewebsite.com/ and J:\Downloads\NewStuff. I don't see any methods on the Uri or FileInfo class that parse a Uri or FileInfo object from a string like I think Dour High Arch was implying.
Is there something I'm missing about using the Uri or FileInfo class that will allow this behavior? If not is there some other class in the framework that does this?
I'd say the easiest way is splitting the strings into parts first.
First delimiter would be spaces, for each word - second would be qoutes (double and single)
Then use Uri.IsWellFormedUriString on each token.
So something like:
foreach(var part in String.Split(new char[]{''', '"', ' '}, someRandomText))
{
if(Uri.IsWellFormedUriString(part, UriKind.RelativeOrAbsolute))
doSomethingWith(part);
}
Just saw at URI.IseWellFormedURIString that this is a bit to strickt to suit your needs maybe.
It returns false if www.Whatever.com is missing the http://
It was not clear from your earlier question that you wanted to extract URL and file path substrings from larger strings. In that case, neither Uri.IsWellFormedUriString nor rRegex.Match will do what you want. Indeed, I do not think any simple method can do what you want because you will have to define rules for ambiguous strings like httX://wasThatAUriScheme/andAre/these part/of/aURL or/are they/separate.strings?andIsThis%20a%20Param?
My suggestion is to define a recursive descent parser and create states for each substring you need to distinguish.
U can use :
(?<type>[^ ]+?:)(?<path>//[^ ]*|\\.+\\[^ ]*)
that will give you 2 groups on each result
type : "http:"
path : //www.thewebsite.com/NewStuff
and
type : "J:"
path : \Downloads\NewStuff
out of the string
"I placed the files on the server at
http://www.thewebsite.com/NewStuff, they can also be reached on your
local network drives at J:\Downloads\NewStuff"
you can use the "type" group to see if the type is http:or not and set action on that.
EDIT
or use regex below if you are sure there is no whitespace in your filepath :
(?<type>[^ ]+?:)(?<path>//[^ ]*|\\[^ ]*)
Try \w+:\S+ and see how well that fits your purposes.

Related paths in 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.

What's the best way to get the name of a folder that doesn't exist?

What's the best way to get a string containing a folder name that I can be certain does not exist? That is, if I call DirectoryInfo.Exists for the given path, it should return false.
EDIT: The reason behind it is I am writing a test for an error checker, the error checker tests whether the path exists, so I wondered aloud on the best way to get a path that doesn't exist.
Name it after a GUID - just take out the illegal characters.
There isn't really any way to do precisely what you way you want to do. If you think about it, you see that even after the call to DirectoryInfo.Exists has returned false, some other program could have gone ahead and created the directory - this is a race condition.
The normal method to handle this is to create a new temporary directory - if the creation succeeds, then you know it hadn't existed before you created it.
Well, without creating the directory, all you can be sure of is that it didn't exist a few microseconds ago. Here's one approach that might be close enough:
string path = Path.GetTempFileName();
File.Delete(path);
Directory.CreateDirectory(path);
Note that this creates the directory to block against thread races (i.e. another process/thread stealing the directory from under you).
What I ended up using:
using System.IO;
string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
(Also, it doesn't seem like you need to strip out chars from a guid - they generate legal filenames)
Well, one good bet will be to concatenate strings like the user name, today's date, and time down to the millisecond.
I'm curious though: Why would you want to do this? What should it be for?
Is this to create a temporary folder or something? I often use Guid.NewGuid to get a string to use for the folder name that you want to be sure does not already exist.
I think you can be close enough:
string directoryName = Guid.NewGuid.ToSrtring();
Since Guid's are fairly random you should not get 2 dirs the same.
Using a freshly generated GUID within a namespace that is also somewhat unique (for example, the name of your application/product) should get you what you want. For example, the following code is extremely unlikely to fail:
string ParentPath = System.IO.Path.Combine(Environment.GetEnvironmentVariable("TEMP"), "MyAppName");
string UniquePath = System.IO.Path.Combine(ParentPath, Guid.NewGuid().ToString());
System.IO.Directory.CreateDirectory(UniquePath);

Categories

Resources