2017-04-01 256 views
-1

我想用File.ReadAllText和FileStream讀取一個文本文件,但由於某種原因我每次都得到System.UnauthorizedAccessException。爲什麼訪問路徑被拒絕?

class consultas 
{ 
    public consultas() 
    { 


    } 

    private string Inativos = @"C:\Users\Mathias Cruz\Desktop\helloWorld\helloWorld\Consultas"; 

    public string getInativos() 
    { 
     try 
     { 
      // string path = Directory.GetCurrentDirectory(); 
      this.Inativos = File.ReadAllText(this.Inativos); 

     } 
     catch(Exception e) 
     { 
      throw e; 


     } 
     return this.Inativos; 


    } 
} 

爲什麼?我在該文件夾中有權限,那麼爲什麼我會得到這個異常?

+0

給這個帖子試一試:http://stackoverflow.com/questions/4877741/access-to-the-path-is-denied – pasotee

回答

1

基於您的代碼,你要麼試圖讀取文件夾,因爲你沒有在你的文件路徑指定擴展這裏:

private string Inativos = @"C:\Users\Mathias Cruz\Desktop\helloWorld\helloWorld\Consultas"; 

它肯定會拋出一個UnauthorizedAccessException錯誤。所以確保你有確切的文件路徑及其擴展名。

+0

謝謝你,我忘了這個細節kkkkkkkk再次感謝。 –

0

因爲path是一個directory.please檢查你的文件地址。 此方法需要文件地址File.ReadAllText(「C:\ yourfile.txt」);