无法从c#.net

问题描述

我正在尝试在C#控制台应用程序中读取文本文件,但是无法从c#.net中指定的文本文件读取,我该如何解决?

我的代码:

string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (File.Exists(docPath))
{
   string text = File.ReadAllText("token.txt");
   Console.WriteLine(text);
}
else
{
   Console.ForegroundColor = ConsoleColor.Magenta;
   Console.WriteLine("Enter your token:");
   string token = Console.ReadLine();

   using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath,"token.txt")))
   {
      outputFile.Write(token);
   }
}

它不会检查用户文档中token.txt的内容,而只是提示用户每次输入其令牌,这会使用户非常烦恼。

该如何解决?

解决方法

这里的问题是您的docPath变量不包含单个文件的路径,而是文件夹的路径。 (C:\ {User} \ Documents)

因此,File.Exists检查将始终失败,因为您将文件夹作为目标。 尝试将您的docPath与实际文件名结合使用,它应该可以工作。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...