如何获取位于Windows应用程序文件夹内的文件的位置

我正在尝试从位于名为“附件”的Windows应用程序文件夹中的CSV文件中读取数据。 在Web应用程序中,您可以使用该文件夹的path

Server.MapPath(@"Attachments/sample.csv"); 

什么是从Windows应用程序的等效呼叫?

以下是我的代码。

 string[] str = File.ReadAllLines(@"Attachment/sample.csv"); // create new datatable DataTable dt = new DataTable(); // get the column header means first line string[] temp = str[0].Split(';'); // creates columns of gridview as per the header name foreach (string t in temp) { dt.Columns.Add(t, typeof(string)); } 

是相对于可执行文件的路径吗? 如果是这样,您可以使用Application.StartupPath来确定程序的启动位置,然后将其与相对文件路径结合以获取完整路径:

 var fullPath = Path.Combine(Application.StartupPath, @"Attachment\sample.csv"); 

如果您的应用程序作为服务运行或使用ClickOnce部署,这将无法正常工作。

Windows应用程序文件夹可以通过此枚举进行标识

 Environment.SpecialFolder.ProgramFiles 

MSDN参考

获取包含实际路径和完整文件名的字符串

 string pathToFile = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); string fullFileName = Path.Combine(pathToFile, @"Attachment\sample.csv"); 

正如Cole Johnson在其评论中指出的那样,如果您的主机操作系统是64位,则存在问题。 在这种情况下,有两个应用程序文件夹。 一个用于64位应用程序,一个用于32位应用程序。 使用NET4,你可以发现当前的操作系统与该属性的位数

 Environment.Is64BitOperatingSystem 

如果为false,则使用不同的枚举

 Environment.SpecialFolder.ProgramFilesX86 

但毕竟,我认为你应该改变你程序的架构。
在Web应用程序中,通常不使用web-root之外的文件夹。
但WinForms应用程序没有这样的限制,然后你可以安装在不同的文件夹中的CSV文件(想到MyDocuments),并通过配置文件中的选项控制硬盘上的实际位置

注意:应用程序文件夹需要特别的权限才能写入(如果您保存附件,则这是另一个选择与应用程序文件夹不同的位置的原因)

你可以这样做,就像这样

 Path.Combine(Application.StartupPath, @"Attachment\sample.csv"); 

史蒂夫打败了我,但是,是检查intellisense任何文件夹,你正在寻找下:

 string path = Environment.GetFolderPath(Environment.SpecialFolder. 

性能

你会发现那里的各种系统路径。