Replace StartInfo.Filename user - c#

I've been googleing for hours without any results.
I'm trying to open up a program that is located in "C:\Users\myUsername\" file, but I cannot find any way to replace MY username to other application-users.
firstProc.StartInfo.FileName = #"C:\Users\Username?\AppData\Roaming\GameWool\Launcher.exe";
firstProc.StartInfo.UseShellExecute = false;
firstProc.StartInfo.RedirectStandardInput = true;
So, I'm basically trying to replace MY \Users\USERNAME. So, if someone is using the application, he's supposed to open the same "game" using their OWN \Users\Username.
I hope you get my point.

You can use System.Environment.UserName, this will retrieve the current username
For some reasons, the path of the user's personnal folders may differs. You can instead use
var UserFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
But since you want to use AppData\Roaming\, this will directly lead you to that folder :
// C:\Users\username\AppData\Roaming
var UserRoamingFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
In your case, for the last example, the path will looks like this :
firstProc.StartInfo.FileName = $#"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\GameWool\Launcher.exe"

Related

how to go one step backwards in path in C#

I want to get the path that my application is located in. I get the physical path by following code:
string filePath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
I get something like this as the result:
D:\\Projects\\UI\\IAC.SMS.MvcApp\\
I know that I can sepetare the string by "\" and combine them together. But is there an easy way to go one step back and get this?
D:\\Projects\\UI\\
You're looking for Directory.GetParent method.
var directoryName = Path.GetDirectoryName("D:\\Projects\\UI\\IAC.SMS.MvcApp\\");
var parentName = Directory.GetParent(directoryName).FullName;
Or
var parentName = new DirectoryInfo("D:\\Projects\\UI\\IAC.SMS.MvcApp\\").Parent.FullName;
Directory.GetParent will work in some cases, but it involves a performance penalty due to the creation of a DirectoryInfo object which will be populated with all sorts of information about the directory that may not be needed (e.g. creation time). I'd recommend Path.GetDirectoryName if all you need is the path, especially since with this method the path doesn't have to exist and you don't have to have permission to access it for the call to succeed.
var filePath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
var parent = Path.GetDirectoryName(filePath);

Folder path before project

I am trying to get a folder path in my C drive that I did not want to hard code with my program.
I know that I can use string path = System.AppDomain.CurrentDomain.BaseDirectory; However its give me : C:\FACE\Camera\Camera\bin\Debug . Which I want to only have C:\FACE\ as I want to initialise something in the FACE folder but outside of my Camera folder. I do not wish to hardcode the file path. Is it possible to do it? Thanks for the help!
You could use the method Directory.GetParent for this purpose:
Directory.GetParent("here you will pass you path");
Update
For your case, you could take that you want as below:
string projectPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string solutionPath = Directory.GetParent(projectPath).Parent.FullName;
string basePath = Directory.GetParent(solutionPath).FullName;
The variable basePath contains that you want.
System.AppDomain.CurrentDomain.BaseDirectory always returns the path of executable assembly.You can use DTE if you are using web application

C# programmatically creating shortcut to directory does not always work

I am trying to programatically create a shortcut to a directory. I have found numerous examples, but none appear to work realiably.
I observe three different results in the produced shortcut's properties:
The Shortcut Type of File is assigned as "Shortcut(.lnk)" which cause the Open With dialog box to pop up asking me to attach an extension to it.
The Shortcut Type of File property is assigned as "File" which does absolutely nothing when double clicked.
Or lastly which is of course my favorite... the Shortcut Type of File property is assigned as: "File Folder" which works like it should.
Here is the code I am currently using... I've tried a few variations of this.
bool IsExists = false;
string icon = appPath + "Welcome.ico";
// Their is a difference to local and ClickOnce App locations... this compensates for it
IsExists = System.IO.File.Exists(icon);
if (!IsExists)
{
icon = appPath + #"bin\Debug\Welcome.ico";
}
var desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
var target = (Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\Artronix\Welcome To FreightWare Online\").Replace(#"\","/");
IWshShortcut shortcut;
var wshShell = new WshShellClass();
shortcut = (IWshShortcut)wshShell.CreateShortcut(Path.Combine(desktop, #"FreightWare Resources.lnk"));
shortcut.IconLocation = icon;
shortcut.TargetPath = Path.GetFullPath(target);
shortcut.Save();
Thank you everyone for your help... I figured it out. I didn't want to post it as an answer, but thought just in case someone else happened to come across this same problem... Although I feel sheepish about my oversight.
It turns out there was nothing wrong with the code. Panhandel gave me a clue to where to find the solution when he made the statement: " I only achieved the first result when the target path didn't exist." Since he was always getting the correct result and he only got the results I was getting when the directory did not exist... I realized the problem may be that I create the directory programatically in one line then in the next create the icon... I needed to give the system more time for the directory to be fully created
Try ShellLink:
using (ShellLink shortcut = new ShellLink())
{
shortcut.Target = Application.ExecutablePath;
shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
shortcut.Description = "My Shorcut Name Here";
shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
shortcut.Save("%HOMEPATH%/Desktop/");
}
I had a slight variant on this issue...
I eventually discovered an additional condition:
The target path has to point at a folder when the shortcut is created (as discussed above)
But also - It appears the target path that's provided also has to be normalized - eg via Path.GetFullPath(possiblyUnNormalizedPath) see
How can one get an absolute or normalized file path in .NET?
Hope this might help someone in the distant future avoid wasting an hour of their life.

Securely enforcing user-input file paths within subdirectories

I know the solid security recommendation of avoiding accepting user input that you then use to choose a path to read/write a file. However, assuming you have a base directory you want to keep within (such as the root of an ftp folder), how do you best ensure that a given user input keeps us within that folder?
For instance,
Path.Combine(_myRootFolder, _myUserInput)
could still take us outside of _myRootFolder. And this could also be dodgy
newPath = Path.Combine(_myRootFolder, _myUserInput)
if (newPath.StartsWith(_myRootFolder))
...
given something like "/back/to/myrootfolder/../../and/out/again" from the user. What are the strategies for this? Am I missing a blindingly obvious .NET method I can use?
Within ASP.NET applications you can use Server.MapPath(filename) which will throw an exception if the path generated goes outside of your application root.
If all you want is a safe file name and you just want all files in there it becomes simpler;
FileInfo file = new FileInfo(
Server.MapPath(
Path.Combine(#"c:\example\mydir", filename)));
If you're outside of ASP.NET like you indicate then you could use Path.GetFullPath.
string potentialPath = Path.Combine(#"c:\myroot\", fileName);
if (Path.GetFullPath(potentialPath) != potentialPath)
// Potential path transversal
Or you call Path.GetFullPath and then check the start of it matches the directory you want locked to.
I know, that this thread is quiet old, but to prevent following readers from writing code with potential security errors, I think I should point out, that using Path.Combine(arg1, arg2) isn't save when arg2 is directly based on user input.
When arg2 is for example "C:\Windows\System32\cmd.exe" the arg1 parameter will be completely ignored and you grant the users of your API or server application full access to the whole file system.
So please be very careful with using this method!
I came up with this solution that should (afaik) be secure:
public static string SecurePathCombine(params string[] paths)
{
string combinedPath = "";
foreach (string path in paths)
{
string newPath = Path.Combine(combinedPath, path);
if (!newPath.StartsWith(combinedPath))
return null;
combinedPath = newPath;
}
if (Path.GetFullPath(combinedPath) != combinedPath)
return null;
return combinedPath;
}
Edit: There is a new Path.Join() method now. Please use that one instead of the code above.
I believe Path.FullPath will do what you need (I didn't test this though):
string newPath = Path.Combine(_myRootFolder, _myUserInput);
string newPath = Path.FullPath(newPath);
if (newPath.StartsWith(_myRootFolder)) ...
Well, in your example of an FTP server, you should set the users home-directory, and permissions appropriately, such that they can't navigate out of the folder. Any reason you can't do that?
You can parse input string and cut ../ with regex.

How can i get the path of the current user's "Application Data" folder?

1)how can i find out the Windows Installation drive in which the user is working.? I need this to navigate to the ApplicationData in DocumentsandSettings.
2)Also how can i get the user name too so that i can goto ApplicaitionData.? Eg: "D:\Documents and Settings\user\Application Data".
Look at combining Environment.GetFolderPath and Environment.SpecialFolder to do this.
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Depending on what you are doing you might also want to look at
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
If the user is on a domain it will only be stored in their local AppData folder and not synced with their roaming profile.
Have a look at the Environment.SpecialFolders
Environment.SpecialFolder.ApplicationData;
Environment.SpecialFolder.System
that should get you round the username requirement as well.
Have a look at the System.Environment class and its properties and methods, e.g:
string systemDir = System.Environment.SystemDirectory;
string docs = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.MyDocuments));
string systemDrive = System.IO.Path.GetPathRoot(systemDir);
The first one returns "C:\Windows\system32" for example and the second one "C:\Documents and Settings\USERNAME\My Documents".
Try this:
string filePath = Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
1)how can i find out the Windows Installation drive in which the user
is working.?
var systemDrive = Environment.ExpandEnvironmentVariables("%systemdrive%");
I need this to navigate to the ApplicationData in
DocumentsandSettings.
You don't really require to fetch the value of either system drive or currently logged in user name to achieve this. There are predefined environment variables %localAppData% and %appData% which give you fully qualified path of these directories as shown in the code below:
var localApplicationData = Environment.ExpandEnvironmentVariables("%localappdata%");
//this gives C:\Users\<userName>\AppData\Local
var roamingApplicationData = Environment.ExpandEnvironmentVariables("%appdata%");
//this gives C:\Users\<userName>\AppData\Roaming
2)Also how can i get the user name too so that i can goto
ApplicaitionData.? Eg: "D:\Documents and Settings\user\Application
Data".
Again, you don't need user name to get the application data path as I've discussed above. Still, for the sake of knowledge you can fetch it from %username% environment variable as shown below:
var currentUserName = Environment.ExpandEnvironmentVariables("%username%");

Categories

Resources