2016-09-19 53 views
0

The folder the .txt-file is inDirectoryNotFoundException了未處理而使用ReadAllLines C#

下面一段代碼是用於調用.txt-file並把它變成串的代碼。

string[] lines = System.IO.File.ReadAllLines(@"C:\This PC\Documents\Visual Studio 2015\Projects\test_read_txt\bin\Debug\read.txt"); 

爲什麼C#不能識別.txt-file的位置? 我試過StreamReader,但後來無法修改讀取。

class Program 
{ 
    static void Main(string[] args) 
    { 
     // Define our one and only variable 
     string[] M = new string[13]; 

     // Read the text from the text file, and insert it into the array 
     StreamReader SR = new StreamReader(@"read.txt"); 

     for (int i = 0; i < 13; i++) 
     { 
      M[i] = SR.ReadLine(); 
     } 

     // Close the text file, so other applications/processes can use it 
     SR.Close(); 

     // Write the array to the Console 

     Console.WriteLine("The array from the txt.file: "); 


     for (int i = 0; i < 13; i++) 
     { 
      Console.WriteLine(M[i]); // Displays the line to the user 
     } 

     // Pause the application so the user can read the information on the screen 
     Console.ReadLine(); 

     if (2 == 2) 
     { 
      M[1][1] = 1; 
     } 
    } 
} 

它不承認M[1][1]作爲第二數組的第二個元素,因爲它只能讀取該文件,並沒有轉化爲多維數組。下面的代碼可以用於上述問題嗎?

tring[] lines = System.IO.File.ReadAllLines(@"C:\This PC\Documents\Visual Studio 2015\Projects\test_read_txt\bin\Debug\read.txt"); 
+0

您似乎缺少路徑中的'test_read_txt'。在屏幕截圖中,該名稱的路徑中有兩個文件夾,並且只包含一個文件夾。 –

回答

3

正如用戶所說,「這臺PC」只是一條顯示路徑,而不是一條真正的路徑。

嘗試使用這個:

string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"Visual Studio 2015\Projects\test_read_txt\bin\Debug\read.txt"); 
    string[] lines = File.ReadAllLines(path); 
+0

它直到顯示相同的錯誤。 –

+0

我看到了,然後將「路徑」變量設置爲完整路徑。例如。 'C:\ Users \ {User} \ Documents \ ... etc' – ThePerplexedOne

+0

如果文本文件與.exe位於同一文件夾中,則可以執行'string [] lines = File.ReadAllLines(「read。 TXT「)' – ThePerplexedOne

2

「C:\此PC \文件」是一個顯示路徑只(在這麼多,因爲它物理上不存在),這實際上相當於「C:\用戶\ {用戶名} \文件」

2

C:\這個PC \文件不正確的路徑

,以獲得正確的文件路徑的最簡單的方法是 轉到文件>安全性能>對象名稱