How do you locate a folder inside of Roaming using C#?
Asked Answered
D

2

6

I'm trying to figure out a way to navigate to a sub folder in Roaming using C#. I know to access the folder I can use:

string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

What I'm trying to do is navigate to a folder inside of Roaming, but do not know how. I basically need to do something like this:

string insideroaming = string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData\FolderName);

Any way to do this? Thanks.

Darbie answered 7/9, 2014 at 1:14 Comment(0)
T
8

Consider Path.Combine:

string dir = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
    "FolderName"
);

It returns something similar to:

C:\Users\<UserName>\AppData\Roaming\FolderName

If you need to get a file path inside the folder, you may try

string filePath = Path.Combine(
    dir,
    "File.txt"
);

or just

string filePath = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
    "FolderName",
    "File.txt"
);
Trichina answered 7/9, 2014 at 1:17 Comment(3)
Let me make the question more clear, because I could see how someone could look at my question differently the way I wrote it. I have already combined the paths to create the folder, but what I need to do next is add a file into it. Would I use dir (Which refers to the string that I used for Path.Combine) to access this folder?Darbie
@Xceptionist You can use the same method or its overload to build the file path.Trichina
@Xceptionist If this answered your question, please mark it as the answer so it can help people who have a similar question in the future.Gisela
A
-1
string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string filePath = Path.Combine(appDataFolder + "\\SubfolderName\\" + "filename.txt");
Alonaalone answered 19/10, 2016 at 4:58 Comment(1)
It seems counterproductive (not to mention messy) to use a combination of Path.Combine and string concatenation - why not just use Path.Combine for the whole thing?Trebuchet

© 2022 - 2024 — McMap. All rights reserved.