2016-09-19 51 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 \文件不正确的路径

,以获得正确的文件路径的最简单的方法是 转到文件>安全性能>对象名称