简体   繁体   English

File.ReadAllText抛出DirectoryNotFoundException

[英]File.ReadAllText throws DirectoryNotFoundException

I have a block of C# code that is trying to open a .txt file. 我有一个试图打开.txt文件的C#代码块。 This text file is in the same project as the block of code that's running. 该文本文件与正在运行的代码块位于同一项目中。 At this time, I'm trying to open the .txt file using the following: 目前,我正在尝试使用以下文件打开.txt文件:

var filePath = @"\Status\new.txt";
try 
{
    var content= File.ReadAllText(filePath);
} 
catch (DirectoryNotFoundException)
{
    Console.WriteLine("Unable to find " + filePath);
}

When this code runs, I get a DirectoryNotFoundException . 当这段代码运行时,我得到一个DirectoryNotFoundException The console shows: 控制台显示:

Unable to find \\Status\\new.txt 找不到\\ Status \\ new.txt

I changed the "Copy to Output Directory" property of the "new.txt" file to "Copy if newer". 我将“ new.txt”文件的“复制到输出目录”属性更改为“如果更新则复制”。 I can see the "new.txt" file in the "bin/Debug/netcoreapp2.1/Status/" directory. 我可以在“ bin / Debug / netcoreapp2.1 / Status /”目录中看到“ new.txt”文件。

I'm running this code currently via an MSTest project. 我目前正在通过MSTest项目运行此代码。 I don't understand why I'm getting this exception though. 我不明白为什么我要得到这个例外。

\\Status\\new.txt will try to load, from the root of the disk, new.txt in the status directory. \\Status\\new.txt将尝试从磁盘根目录加载status目录中的new.txt From your description, this isn't where the file is. 根据您的描述,这不是文件所在的位置。

If you have the file in the same folder as your executable you only need the new.txt , if it's in a subdirectory off of where the executable is, then .\\status\\new.txt should work. 如果文件与可执行文件位于同一文件夹中,则只需要new.txt ,如果文件位于可执行文件所在的子目录中,则.\\status\\new.txt应该可以使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM