简体   繁体   中英

How do I load a file that I bundled with the install of my C# program?

I need to do something like this:

    StreamReader reader = 
new System.IO.StreamReader(@"C:\Program Files\The Awesome Program That I Made\awesomeloadablefile.ldf");

Except I don't know where the user has installed the program. How is my program supposed to know where the installed files are?

I am a noob, in case you hadn't noticed.

You can use Assembly.GetEntryAssembly().Location to get the path on disk of your executable, Path.GetDirectoryName to get the directory it's in, and then Path.Combine to combine the directory name with your file name in that directory. So:

StreamReader reader = new System.IO.StreamReader(Path.Combine(
    Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), 
    "awesomeloadablefile.ldf"));

Try something like this.

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

Assembly.GetExecutingAssembly().Location类的东西应该起作用。

您可以尝试以下方法:

 File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "awesomeloadablefile.txt"); 

Assuming you know the directory structure relative to your executable, you can use Application.StartupPath :

string path = Path.Combine(Application.StartupPath, "awesomeloadablefile.ldf");
StreamReader reader = new System.IO.StreamReader(path);

This will get you a path to the exe directory. I'm assuming that's where you decided to put the file. Otherwise you can specify a had location for it in the installer. Are you using the Visual Studio installer?

Application.StartupPath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM