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

时间:2012-06-20 22:17:52

标签: c# windows filepath

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

获取文件夹的路径
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));
}

4 个答案:

答案 0 :(得分:2)

可以通过此枚举

识别Windows应用程序文件夹
Environment.SpecialFolder.ProgramFiles

MSDN refs

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

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)并通过配置文件中的选项控制硬盘上的实际位置

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

答案 1 :(得分:2)

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

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

如果您的应用作为服务运行或使用ClickOnce部署,则无法使用此功能。

答案 2 :(得分:1)

你可以用类似

之类的东西来做到这一点
Path.Combine(Application.StartupPath, @"Attachment\sample.csv");

答案 3 :(得分:0)

史蒂夫打败了我,但是,请检查intellisense,查找您正在寻找的文件夹:

string path = Environment.GetFolderPath(Environment.SpecialFolder.

属性

你会在那里找到各种系统路径。

相关问题