在源目录中使用文件的C#应用​​程序,如果开始使用其他应用程序,则在查找文件时出错 [英] C# App which uses a file in the source dir, makes error about finding the file if it's started using other apps

查看:72
本文介绍了在源目录中使用文件的C#应用​​程序,如果开始使用其他应用程序,则在查找文件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个C#应用程序,它使用与该应用程序位于同一目录中的文本文件。当我通过双击启动该应用程序时,它可以正常运行。我想使用第4个鼠标按钮启动它,但是当我尝试运行时,应用程序会出现有关查找文本文件的错误。我的应用程序是一个简单的启动器,我希望它的运行就像单击鼠标按钮一样容易。
我如下定义文本文件路径,并使用public static让其他表单也使用该路径并找到文件。

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";

应用程序和文本文件位于>> bin\Debug\

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

错误:
在此处输入图像描述

我使用 Volume 2应用程序(由Alexsandr Irza设计)来定义鼠标的第4和第5按钮的功能。我认为这很奇怪,因为运行我的使用双击的应用程序没有任何错误,它可以读取文本文件并将其写入。
请帮助我修复它。

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.

推荐答案

不要使用 GetCurrentDirectory

如果要查找可执行文件的目录,请使用

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");

这篇关于在源目录中使用文件的C#应用​​程序,如果开始使用其他应用程序,则在查找文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆