Getting a user specific path without knowing the username - c#

I have a HTML file in C:\Users\myusername\AppData\Roaming\myapp\file.html. I am accessing the file through a web Browser in my C# application to preview it from within the app.
However, when the app is put onto another computer, the address in webBrowser1 is still specific to my username, and therefore other people cannot access the preview.
Is there a way to get to the file as a URL in my web Browser without having the hard coded username in the URL?
What I have tried:
C:\Users\%USERNAME%\AppData\Roaming\myapp\file.html
C:\Users\AppData\Roaming\myapp\file.html
Thanks!
Here is the code I used after I was helped:
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string address = Path.Combine(folderPath + #"\myapp\file.html");
webBrowser1.Navigate(address);

If you want to get the name of the current logged in user you have to read Environment.UserName property.
Moreover if you need to access the AppData directory for the roaming user you can get the folder path without hard-coding anything (do not forget that users directory isn't always c:\users on every Windows version and path for AppData may vary too):
string folderPath = Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData);
In you case simply append the file name:
string url = Path.Combine(folderPath, "file.htm");
Notes
If, for any reason, you need to use environment variables then you have first to expand them:
string path = Environment.ExpandEnvironmentVariables(#"C:\Users\%USERNAME%\");

Have a look at this function. It returns the path of Current User's Application Data Folder.
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

Related

How to find the home folder in C# from another directory?

I have deployed a .NET Core webapplication on a Ubuntu 16.04 LTS server using nginx.
I'd like to find this directory:
# Location source code
/home/user-0123456/webapp
From within this location:
// Location compiled code and source to outside world
/var/webapp
In this situation, user-0123456 is fixed, but the fix should be generic. So i.e., it could be different in the future - but you can assume there will always be one user.
I did came across this post, but both these lines:
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)
return /var/www instead of /home/user-0123456/webapp.
Question
So how can I find the root directory of my 'webapp'-dir in the home folder from inside another path?
Simple, you can get the HOME directory with:
System.Environment.GetEnvironmentVariable("HOME");
However, if your application runs under the account www-data, "home" will be the home-directory of the user www-data, and not the user you are currently logged in...
And if you want to get the root-directory of the web-application, that would be
System.IO.Path.GetDirectoryName(typeof(Program).Assembly.Location);
But if you want to map the directory in /var/xyz to /home/user-123/xyz, then you do:
string user = System.Environment.GetEnvironmentVariable("USER");
string app = System.IO.Path.GetDirectoryName(typeof(Program).Assembly.Location);
app = app.Substring("/var/".Length);
string sourceDir = System.IO.Path.Combine("/home", user, app);
If you actually need the home directory of another user, this is how you get it by user-name:
string username = "user-123";
Mono.Unix.Native.Passwd pwd = Mono.Unix.Native.Syscall.getpwnam(username);
// pwd.pw_uid
string dir = pwd.pw_dir;
System.Console.WriteLine((dir));
The last one requires Mono.Posix compiled for .NET-Core/NetStandard2.0 and the native library that mono.posix wraps its Linux-syscalls around.

Run an .exe file from C:\Users\user\AppData\Roaming\ect from different PC's

I have a Windows From application that runs several things on voice commands.
On a certain command I want to start Spotify, as you may know Spotify is installed in C:\\Users\\Danny\\AppData\\Roaming\\Spotify\\Spotify.exe.
This isn't a problem as long as my application is installed on my own PC. But when I want to run my app on different PC's this of course won't work.
Is there a way to maybe use a generic path to run this application?
Use the Envoirment.SpecialFolder.
If you use the Environment.SpecialFolder than it will get a path for the current user, so you don't have to type the path manually:
This example will get the path for the appdata folder. From there you can go further into the file structure, like I did with the Path.Comine() to prevent any path combine errors.
// Get appdata folder path for every user
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// Your extension to Spotify.exe
string extentionToPath = "Spotify\\Spotify.exe";
// Finalpath, combine the appdata with your own extention.
string finalPath = Path.Combine(appDataPath, extentionToPath);
// one line to get the path
string finalPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\\Roaming\\Spotify\\Spotify.exe");
So now as you can start the process by doing this:
Process.Start(finalPath);

Environment.SpecialFolder.ApplicationData returns the wrong folder

I have a strange problem: my .NET 4.0 WPF application is saving data to the ApplicationData folder.
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\myProgram\\";
99.9% of the cases are working great, but on some computers it returns the wrong folder - instead of returning the user folder it returns another folder:
C:\Users\<user>\AppData\Roaming\myProgram\ --correct
C:\Users\s\AppData\Roaming\myProgram\ --wrong
The wrong folder has no write/read permission so my program doesn't work.
It seems the program is running under a different user, but if I check the Task Manager the user is the logged one.
The problem seems to be occurring with domain users with few permissions.
Do you also create a text file to write?
If so save a file such as:
String path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var filePath = Path.Combine(path, "filetowrite.log"); // Handles whether there is a `\` or not.
if (File.Exists(filePath))
{
......................
}
Note also before doing any file operations, one should check if directory exists.

C# Copy file to folder with permissions

I'm writing a program that, among other things, needs to copy a particular file to a network folder. Since I'm on a company network, the credentials needed to access that folder are the same as my Windows credentials.
The program works if I open the folder in Explorer, provide my username and password, and then run the uploader. It doesn't work without first providing that username and password.
How do I tell System.IO to supply my DefaultNetworkCredentials to the Copy method? Or is there another method I can use to get this done?
string pathToFile = "myfile.csv";
string pathToRemoteFile = "\\server.domain.tld\Documents\Subfolder\myfile.csv"
System.IO.File.Copy(pathToFile, pathToRemoteFile); // Fails with IOException "can't find network path"
Thanks!
~ Wogan
The error suggests that it is an incorrect path rather than a permissions problem.
Try this:
string pathToRemoteFile = #"\\server.domain.tld\Documents\Subfolder\myfile.csv"
[The # is the string literal quoting symbol; without it the backslash is a special character]

ASP.Net search subdirectory

How do I search a sub directory in my ASP.Net web site?
I know if this was a regular Winform project, I could easily get it by the following:
Environment.CurrentDirectory
or
System.IO.Directory.GetCurrentDirectory()
then
string[] directories = System.IO.Path.Combine(Environment.CurrentDirectory, "Portfolio")
How do I build the path to a subfolder called Portfolio in ASP.Net?
I'm having a problem building everything from the http://??????????/Portfolio. How do I find the ?????? part?
I tried the code above but got a completely different directory...
I don't want to hard code everything before that last subfolder because it will be different on another server.
Calling Directory.GetCurrentDirectory() can be misleading when calling it from an ASP.NET app. The best way to do get around this is to use Server.MapPath() instead, which will allow you to map a web folder to its location on disk.
So for example, running this code:
string path = Server.MapPath("~/Portfolio");
will set 'path' equal to the location of that folder on disk.
If you're running this code from outside the context of a Page or control class, you won't be able to access the Server object directly. In this case, your code would look like this:
string path = HttpContext.Current.Server.MapPath("~/Portfolio");
If I understand you right, you can just access it with:
"/portfolio"
The system will concatenate "/portfolio" to the url, if, for example it is "http://site.com" you will get "http://site.com/portfolio"
If you want the physical path, you can use
server.mappath("/portfolio")
and it will return the physical directory associated (for example E:\websites\site\portfolio")
the following piece of lines gets you to the 'bin' directory
Assembly asm = Assembly.GetExecutingAssembly();
String strAppHome = Path.GetDirectoryName(asm.CodeBase).Replace("file:\\", "");

Categories

Resources