2014-03-03 55 views
0

我正在阅读和写作一些文本文件,我目前正在使用设置路径。如何更改该设置路径以使用可执行文件所在的文件夹?File.ReadLines相对于应用程序可执行文件的路径?

例如:

File.ReadLines(@"D:\Users\MyUserName\Desktop\MyApplication\names.txt").Skip(1).ToList(); 

和...

File.WriteAllLines(@"D:\Users\MyUserName\Desktop\MyApplication\names.txt", lines); 

和...

using (StreamWriter writer = new StreamWriter(@"D:\Users\MyUserName\Desktop\MyApplication\names.txt", true)) 
{ 
    writer.WriteLine(myText); 
} 

还需要在IDE中测试时工作(Visual Studio中) 。

+0

只需使用的文件名。工作目录始终是可执行目录。 –

+0

@SimonWhitehead:那根本不是真的。如果您从其他目录运行“c:\ foo \ program.exe”,则当前工作目录将是您所在的目录,* not *“c:\ foo \”。 –

回答

4

该路径相对于当前工作目录。在IDE中运行时,这将是可执行文件所在的目录。否则,它通常是您启动程序的目录。因此,如果你的当前目录(在命令行上)是C:\ foo并且你输入了命令“C:\ bar \ myprogram.exe”,你的程序将从C:\ foo开始,如果你试图打开文件“fooby.txt”,它会查找“C:\ foo \ fooby.txt”。有关如何获取可执行文件路径的信息,请参阅How do I get the name of the current executable in C#?

1
Assembly.GetEntryAssembly().Location 

如果你的WinForms是应用程式你可以使用

System.Windows.Forms.Application.StartupPath 

默认情况下它会指出当前目录作为@JimMischel说。

所以最好避免使用像这样的文件名File.ReadLines("names.txt");而不是提供完整的文件路径。

+0

'File.ReadLines(“names.txt”)'不一定会从包含.exe的目录中读取。它将从当前工作目录读取。 –

+0

@JimMischel谢谢,更新回答 –

0

您还可以使用Environment.CurrentDirectory来获得当前的应用程序文件夹 检查LINK更多细节

+0

CurrentDirectory是不同的检查吉姆的答案 –

相关问题