Search code examples
c#directorystreamreaderfile.readalllines

DirectoryNotFoundException was unhandled while the use of ReadAllLines C#


The folder the .txt-file is in

The following piece of code is the code used to call the .txt-file and turn it into strings.

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

Why wont C# recognize the location of the .txt-file? I tried with StreamReader but then the read could not be modified.

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

It did not recognize M[1][1] as the second element of the second array because it only read the file and did not transform it into a multidimensional array. Can the following code be used for the above described problem?

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

Solution

  • As users have stated, "This PC" is simply a display path, not a real one.

    Try using this instead:

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