【问题标题】:DirectoryNotFoundException was unhandled while the use of ReadAllLines C#使用 ReadAllLines C# 时未处理 DirectoryNotFoundException
【发布时间】:2016-09-19 14:18:50
【问题描述】:

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

【问题讨论】:

  • 您的路径中似乎缺少test_read_txt。从屏幕截图中可以看出,路径中有两个具有该名称的文件夹,而您只包括一个。

标签: c# directory streamreader file.readalllines


【解决方案1】:

正如用户所说,“这台电脑”只是一个显示路径,而不是真实路径。

尝试改用这个:

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

【讨论】:

  • 我明白了,然后将“路径”变量设置为完整路径。例如。 C:\Users\{User}\Documents\...etc
  • 如果文本文件与.exe在同一个文件夹中,你可以这样做string[] lines = File.ReadAllLines("read.txt")
【解决方案2】:

“C:\This PC\Documents”只是一个显示路径(实际上它并不存在),这实际上等同于“C:\Users\{username}\Documents”

【讨论】:

    【解决方案3】:

    C:\This PC\Documents 路径不正确

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

    【讨论】:

      猜你喜欢
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多