使用ReadAllLines C#时,DirectoryNotFoundException未处理

时间:2016-09-19 14:18:50

标签: c# directory streamreader file.readalllines

The folder the .txt-file is in

以下代码是用于调用.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");

3 个答案:

答案 0 :(得分:3)

正如用户所说,&#34;这台PC&#34;只是一个显示路径,而不是真实路径。

请尝试使用此代码:

    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);

答案 1 :(得分:2)

&#34; C:\此PC \ Documents&#34;只是一个显示路径(实际上它不存在),这实际上相当于&#34; C:\ Users \ {username} \ Documents&#34;

答案 2 :(得分:2)

C:\此PC \ Documents不是正确的路径

获取正确文件路径的最简单方法是 转到文件属性&gt;安全&gt;对象名称