2011-08-03 125 views
1

我有这个文件:C:\ Documents and Settings \ extryasam \ My Documents \ Visual Studio 2010 \ Projects \ FCR \ WebApplication4 \ config \ roles.txt我想将它导入到我的C#应用​​程序。如果我插入完整路径,那么可以,但我想要做类似于我们在网站上做的事情,那就是“\ config \ roles.txt”C#路径问题

但是,下面的代码不起作用。

这是我的代码:

public string authenticate() 
    { 
     WindowsIdentity curIdentity = WindowsIdentity.GetCurrent(); 
     WindowsPrincipal myPrincipal = new WindowsPrincipal(curIdentity); 

     //String role = "NT\\Internet Users"; 

     //string filePath = Server.MapPath("config/roles.txt"); 
     //string filePath = (@"~/WebApplication4/config/roles.txt"); 
     //string filePath = Path.GetDirectoryName(@"\config\roles.txt"); 
     string filePath = Path.GetPathRoot(@"/config/roles.txt"); 
     string line; 
     string role = ""; 

     if (File.Exists(filePath)) 
     { 
      StreamReader file = null; 
      try 
      { 
       file = new StreamReader(filePath); 
       while ((line = file.ReadLine()) != null) 
       { 
        role = line; 
       } 
      } 
      finally 
      { 
       if (file != null) 
       { 
        file.Close(); 
       } 
      } 
     } 

     if (!myPrincipal.IsInRole(@role)) 
     { 
      return "401.aspx"; 
     } 
     else 
     { 
      return "#"; 
     } 
    } 
+3

它怎么会出错? – Jodrell

+0

你是说你想从WinForms或Console应用程序访问Web应用程序中的文件? –

+0

这篇文章被标记为ASP.NET,所以我认为该文件在ASP.NET中访问服务器端 –

回答

2

在ASP.NET中,您可以使用~/config/roles.txt - 结合Server.MapPath(),您可以得到完整路径。

[...] ASP.NET includes the Web application root operator (~), which you can use when specifying a path in server controls. ASP.NET resolves the ~ operator to the root of the current application. You can use the ~ operator in conjunction with folders to specify a path that is based on the current root. (see http://msdn.microsoft.com/en-us/library/ms178116.aspx)

所以,你可以尝试以下方法:

string filePath = System.Web.HttpContext.Current.Server.MapPath("~/config/roles.txt"); 
+0

我正在C#中这样做# –

+0

C#只是语言。你可以用C#编写ASP.NET应用程序......你有什么样的应用程序? ASP.NET(WebForms),WinForms,控制台,WPF ...?您的应用程序位于何处(相对于文档?) –

+0

ASP.NET Web应用程序是我正在使用的应用程序的类型 –

0

你应该选择您的文件,并按下F4,然后选择复制到输出目录。那么你将能够使用它

1

您可以使用Server.MapPath将指定的相对或虚拟路径映射到服务器上相应的物理目录。

1

既然你在本地工作,你可以使用该文件的绝对路径,它会起作用。 但是,当包含roles.txt文件的Web应用程序将部署在某个Web服务器上并且用户将尝试从另一台机器访问此文件时,情况如何呢? 您可以使用以下方法从Windows应用程序访问托管的Web服务器上的文件:

using (var stream = new WebClient().OpenRead("your_web_application_root_url/configs/roles.txt")) 
using (var reader = new StreamReader(stream)) 
{ 
    Console.WriteLine(reader.ReadToEnd()); 
} 

可以在网络不太好主意警告说,股票的安全设置。

+0

我在CVS上工作,那是当我遇到问题时,我注意到我需要一些能够让我走的路径。安全是重中之重,所以你的方法不是真正的选择。我在看Path类,我脑子里想的是这样的: “string filePath = Path.GetDirectoryName(@”\\ config \\ roles.txt“);”但它仍然不起作用 –