Get files from custom folder inside C# project

2020-07-08 08:00发布

问题:

First time poster (and newbie).

I've created a C# winform application. I've added a "Documents" folder in which I've added 5 PDF files.

From within my Form1, I've added a button and inside the button click event, I'm trying to get the files from that "Documents" folder.

I've googled around and found stuff like this:

string[] arr = Directory.GetFiles(string path);

But I do not wish to "hardcode" the path of my "Documents" folder. I'd like to know if there's a way (more dynamic) to obtain the path of my "Documents" folder.

I've also found these:

string path1 = Path.GetDirectoryName(Application.ExecutablePath);
string path2 = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

But they always bring me to my \bin\Debug folder.

I'll take all the help I can get! Thanks!

回答1:

Environment.SpecialFolder enumeration you mean?

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

Or am I misreading the question?

EDIT

I guess I did misread, my apologies. Try this:

string documents = Path.Combine(
                     Path.GetDirectoryName(Application.ExecutablePath),
                     "Documents"
                   );

This is also assuming you're including the items from the "documents" folder as resources so the executable will be able to see them.



回答2:

You will either have to tell Visual Studio to copy the files to output or, as i would probably do it, have them reside in %APPDATA%