C# App which uses a file in the source dir, makes error about finding the file if it's started using other apps

血红的双手。 提交于 2019-12-08 09:17:49

问题


I'm making a C# application which uses a text file located in the same directory as the application. when I start the app by double click, it runs without any problem. I want to start it using 4th mouse button but when I try, app makes error about finding the text file. My app is a simple launcher and i want it to run as easy as clicking a mouse button. I defined text file path as below and I used public static to let other forms use the path and find the file too.

public static string list = System.IO.Directory.GetCurrentDirectory() + @"\list.txt";
Also tested: 
public static string list = Environment.CurrentDirectory+ @"\list.txt";

The app and the text file are located in>> bin\Debug\

Error: enter image description here

I use "Volume 2" Application (by Alexsandr Irza) to define functionality of 4th and 5th buttons of my mouse.I think it's so weird because running my app using double click makes no error and it can read the text file and write to it. Please help me to fix it.


回答1:


Don't use GetCurrentDirectory; that can change as your program runs.

If you want to find the directory of your executable, use

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

To get the path of a file in the same directory as your executable:

var filePath = System.IO.Path.Combine(path, "list.txt");



回答2:


How about something like: string path = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\'));?



来源:https://stackoverflow.com/questions/52546102/c-sharp-app-which-uses-a-file-in-the-source-dir-makes-error-about-finding-the-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!