C# Path.Combine for virtual paths? - c#

I have a .NET MVC application where I am building a virtual path using the below:
Path.Combine("~/Documents/", "application", "username");
The output from this is "~/Documents/application\\username". This causes an error when passed to a Telerik RadFileExplorer however if I manually build the path as "~/Documents/application/username" it works fine. The example above uses strings but the actual code is using variables.
I'd prefer not to use String.Replace if possible... Is there an alternative to Path.Combine that would produce this output? "~/Documents/application/username"

Path.Combine adds the / for you, so you don't need to add it when combining the path.
Try like this: Path.Combine("~/Documents", "application", "username");

There are a lot of alternatives for combining the a path (which is basically a string).
you can use the $ - string interpolation and put the parameters like this: $"~/{Documents}/{application}/{username}" which is more readable than replace.

edit: just saw Raziel's answer, which is probably much better/simpler..
Livio's comment is in general incorrect. That's only true if run on a Unix-based system. If run on a Windows system Path.Combine defaults to backslashes unless otherwise specified.
From the documentation of Path.Combine it only uses the forward slash if it's explicitly included in the path component. I would suggest writing a function for the latter two arguments that just appends a forward slash to the end (and maybe also ensures that there are no slashes at the beginning because that would cause them to be interpreted as absolute paths and overwrite everything before that).

Related

Expand paths with tilde (~) in .NET Core

If I use a disk (not URL) path with ~, e.g. ~/mike/foo, then the runtime appends it to the current working directory instead of expanding it.
These don't work:
Path.GetFullPath
Path.Combine
Is there a built-in .NET Core function that would expand such a path safely, cross-platform?
My cross-platform workaround:
myPath = myPath
.Replace("~", Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))
.Replace("//", "/");
But there are presumably edge cases (especially cross-platform), as always. So a built-in .NET Core function, if one exists, is preferable.
(Please add your answer and I'll accept it.)

Are backslashes at the end of folder paths relevant?

I am writing a program that copies all files and directories from a source location into a target location. Both locations are provided by the user.
I was just thinking about checking whether the location paths have a backslash "\" at the end, when I decided to run some tests and from what I see it doesn't matter if you tell c#
File.Copy("C:\\test", "D:\\test")`
or
File.Copy("C:\\test\\", "D:\\test\\")`
Am I wrong? Does a backslash at the end of a file path matter?
Update:
On Windows, you apparently cannot name a file and folder the same, so it won't matter there. You should still use a (back)slash for good style and cross-platform compatability. Some software or libraries might even depend on it.
Original Answer:
A folder is generally ending in \ (or /), because there might be a file with no extension, named test. For example, these two could coexist (Linux [notice the different capitalization]):
Folder: /Users/nikxda/Docouments/Test/
File: /Users/nikxda/Docouments/test
If you work case-sensitive, then you could in fact ignore it on Windows. I'd still recommend using a trailing slash, just for
Clarification (specify it is a folder)
Good style (following conventions)
Compatibility (other software, libraries, etc. might depend on it)
Cross platform (OSX, ...)
So yes, you should always use a (back)slash at the end of your path if referring to folders.
It should make no difference, because - on windows - you cannot have a folder "test" and file named "test" without extension in the same parent directory at the same time.
However, it will be much more cleaner to have a trailing backslash within your code, because this leaves no room for speculation. And it will be better for cross-plattform purposes as well.
Thinking of URIs for example, it can definitely make a difference between a trailing slash or no trailing slash, by the way.
TLDR: Use a trailing (back)slash, please :-)

I'm writing C# code that has to run on windows and linux (under mono). Easy way to handle file paths on both?

I'm writing a mod for Kerbal Space Program that logs data to a text file for use in outside tools (matlab, etc). KSP works on both Linux and Windows and I would like my mod to play nice on both. I was kind of hoping that the mono implementation on linux would just do the smart thing and translate the \'s to /'s, especially since I'm just working with Directory.GetCurrentDirectory as my base, so I don't have to worry about detecting/specifying things like c:\ vs /.
An acceptable answer (at least for now) would be a decent way to determine which platform I'm running on and just generate the strings differently (use a seperator char variable that I can set instead of slash string literals). I could look that up myself though, I'm kind of hoping there's a slick solution. I tried Googling/searching on here but nothing really stood out.
Use Path.PathSeparator. \ on Windows, / on Unix.
If you're looking to combine directory names, you can use Path.Combine.
To get the root directory (i.e. / or C:\, you can use Path.GetPathRoot(Directory.GetCurrentDirectory())).
More info in the Path docs.
Mono provides IOMap to convert pathnames, so you can use backslashes happily in your code and then use MONO_IOMAP=all mono something.exe to start your program. Mono has a page with suggestions on application portability.
Use the System.Path.* as much as you can. It will avoid you from having to do specific OS checks to determine temp dirs, app locations, data/Desktop/Doc locations...
And use Path.Combine and stay away from having to using path separators. If you are hand parsing and building paths using Path.PathSeparator, ask your why? The odds are there is a std framework method that does what you want. KISS ;-)

Validate a path

Is there any way of validating if a path can be correct in .net or do I need to write something myself?
What I have is a string that is supposed to be a valid path such as:
\\server\shared\folder\file.ext
c:\folder\file.ext
.\folder\file.ext
\folder\file.ext
%appdata%\folder\file.ext
The path does not need to exist on the machine where this is run and the network does not need to be accessible, I'm only interested to see if the path could ever be valid.
Was thinking about splitting the path into filename and path and then using the Path.GetInvalidPathChars() and Path.GetInvalidFileNameChars() arrays to check if the path contains invalid filenames which would at least be a start. But there may be better ideas?
You can use the following library which is part of NDepend: NDepend.Helpers.FileDirectoryPath It has rich API for processing pathes.
Can't you define a valid set of regular expressions? I think we can define the patterns..

How to recognize a path inside a string

Just that... I get a string which contains a path to a file plus some arguments. How can I recognize the path? I thought about the index of the '.' in the file... but I don't like it.
What about using regular expressions? Can anyone point me in the right direction?
Regards
Edit: Theses are valid entries...
somefile.msi /a
C:\MyFolder\SomeFile.exe -i -d
I don't care much about the arguments cause once I have the path I'll assume the rest are arguments
You can use System.IO.Path, and it's static methods.
bool isPath = System.IO.Path.GetDirectoryName(#"C:\MyFolder\SomeFile.exe -i -d") != String.Empty;
if (isPath)
{
Console.WriteLine("The string contains a path");
}
The static Path class has several other methods which are useful as well, like .GetFilename, .GetExtension and .GetPathRoot.
You can also probably use System.IO.Directory and System.IO.File for additional features.
You can't unless you access the file system, because paths may contain spaces.
So you might test each possible "file" using File.Exists. A string.Split() will help you here.
For non-MSI programs, UninstallString is passed to CreateProcess, so you probably want to replicate its method of determining the filename. Read http://msdn.microsoft.com/en-us/library/ms682425.aspx, especially the notes for lpApplicationName and the second half of lpCommandLine.
Programs installed by MSI have a separate system (msi!MsiConfigureProduct or msi!MsiRemovePatches).
Well, before you tackle finding the path in the string, you need to outline a set of rules for what a path in this context
This is, for the operating system, a valid filename: a
Since no directory information is specified, the current directory will be used. The file has no extension.
But is still a filename.
Is this a path in your context? Or do you mean something that has directory information as well?
Examples of what you need to handle would be useful.
The normal way in this case is to tokenise by spaces (and use quotes for a filename with spaces in). Then use / or - for arguments. I think you'll be better off using a standard, accepted format than working for only a subset of cases.
Mmm, I believe that the only reliable way to do that is to access the filesystem, supposing it is reachable.
I would cut the string at the spaces, starting from the end, and take the longest that exist on the filesystem.
For example:
C:\My Folder\Some File.exe -i -d
=>
C:\My Folder\Some File.exe -i -d (no, although it might exist!)
C:\My Folder\Some File.exe -i (no)
C:\My Folder\Some File.exe (yes => That's this one)
You must take in account relative paths, and files in PATH (like your first example, ie. all exe files - even worse, you can write foo.exe or foo on the command line!).
Plus you can often write stuff like notepad/p, which doesn't simplify the algorithm, knowing that C:/windows/notepad.exe is a valid path in XP! :-)
If you have any control over the string I'd recommend you change the way it is represented. One way would be to use URL-style parameters - e.g. fileName=myFile;arg1=value, etc. Then it's trivial to parse on keys.
The problem with any sort of raw parsing scheme is that the trailing data is not necessarily going to be clean. Also your filename is not necessarily NOT going to have spaces, extraneous "."'s etc. So whatever you decide is liable to not be correct 100% of the time.
Have a look at SYstem.IO.Path, you probably want GetDirectoryName(string)
thanks all for the answers.. there are a couple of posts I'd like to mark as the answer... what do you do in these cases?
Just in case somebody wants to see what I'm working on, it's a small application used to uninstall software from my computer. I posted the code, so feel free to download it and take a look at it.
The reason to this post is a good way to implement the private ProcessStartInfo GetProcessInfo(string uninstallString) method.
The reason to this project is posted here...

Categories

Resources