2011-12-21 155 views
0

我有即时阅读到流阅读器的链接 - @“C:tweets.txt \用户\詹姆斯\桌面\”如何创建相对文件路径

我在同一文件夹中的文本文件源代码和.exe

我会如何将'@“C:\ Users \ James \ Desktop \ tweets.txt''更改为相对文件路径?

+0

对不起不清楚,你问什么? “通用”为什么? – Tigran 2011-12-21 19:09:22

+0

你的意思是**相对的**路径吗? – Adam 2011-12-21 19:10:40

+0

必须是相对的吗?我被告知它是通用的? – qwertyuywertwer 2011-12-21 19:11:18

回答

1

您可以通过使用Assembly.GetExecutingAssembly().Location来获取当前程序集/ exe路径。一旦你,你可以很容易地在路径追加文本文件名来访问您的文本文件

您还可以得到的文件夹通过使用System.IO.Path.GetDirectoryName (Assembly.GetExecutingAssembly().Location)

包含您的exe文件被嘘,你可以做提到的路径

Path.Combine(System.IO.Path.GetDirectoryName (Assembly.GetExecutingAssembly().Location), "Text File Name"); 
+1

值得注意的是应该调用'Path.Combine(string,string)'而不是仅仅进行字符串连接。 – 2011-12-21 19:15:11

1

你的意思是相对路径吗?你可以试试这个:

Uri srFile = new Uri(@"C:\Users\James\Desktop\tweets.txt"); 

Uri projFile= new Uri(@"C:\MyprojectDirectory\Project\..."); 



Uri relativePath = projFile.MakeRelativeUri(srFile); 
+0

我必须提交一份归档到文件中的分配。我被告知有一种方法可以从同一个文件夹中读取它?不管它在哪里? – qwertyuywertwer 2011-12-21 19:14:06

+0

您使用'Haris Hasan's'来获取'projFile'的值。 – keyboardP 2011-12-21 19:15:35

0

可以使用Application.StartupPath属性:

using System.Windows.Forms; 
... 
string myApplicationPath = Application.StartupPath;