2011-08-03 83 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「);」但它仍然不起作用 –