C#找不到文件

我有一个C#Visual Studio 2008表单,需要读取相关文件’character / attacks.txt’的内容.File.Exists()在运行时返回false,即使我很肯定我的目录已经排序。 码:

try { System.IO.StreamReader file = new System.IO.StreamReader("character/attacks.txt"); int counter = 0; int numberOfLines = 0; string line; while ((line = file.ReadLine()) != null) { numberOfLines++; } string[] attacks = new string[numberOfLines]; while ((line = file.ReadLine()) != null) { attacks[counter] = line; counter++; } file.Close(); print(attacks.ToString()); } catch (Exception ex) { print("ERROR"); print("Did you edit any files?"); print(ex.ToString()); } 

exception错误:

 System.IO.FileNotFoundException: Could not find file 'D:\Users\Andrey\Desktop\Turn\character\attacks.txt'. File name: 'D:\Users\Andrey\Desktop\Turn\character\attacks.txt' at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) at System.IO.StreamReader..ctor(String path) at TurnByTurn.Form1.button1_Click(Object sender, EventArgs e) in D:\Users\Andrey\Desktop\C#\TurnByTurn\TurnByTurn\Form1.cs:line 52 

我正在从Python移植我的代码,从来没有遇到任何麻烦。 提前致谢!

这很奇怪。 计算机似乎坚信D:\Users\Andrey\Desktop\Turn\character\目录中没有attacks.txt文件,但你说它肯定存在。 你们其中一个人肯定是错的,多年来我学会了计算机比我更频繁。

您确定您的文件实际上有.txt扩展名,而不是.txt.somethingelse扩展名吗? 如果在Windows shell中关闭了文件扩展名的显示,则可能缺少此额外的文件扩展名。 但是,计算机内部并没有遗漏它,并且它看到的文件与您请求的文件完全不同。 那个人有同样的问题。

要重新配置Windows资源管理器:

  1. 打开“控制面板”文件夹。
  2. 单击“文件夹选项”。
  3. 切换到“查看”选项卡。
  4. 在“高级设置”列表框的项目列表中找到“显示隐藏文件,文件夹和驱动器”单选按钮,并确保选中它。
  5. 单击确定。

这个问题的其他答案确实提出了一些很好的建议。 其中:

  1. 确保如果在字符串文字中使用反斜杠(这是标准的Windows路径分隔符),则使用第二个反斜杠“转义”它们。 这需要的原因是反斜杠被C#编译器解释为转义字符,它允许您输入类似\t来插入选项卡。 如果要插入常规反斜杠,则必须转义escape- \\ 。 这就是当您尝试使用单个反斜杠时出现错误的原因。

  2. 您可以告诉C#编译器完全按照键入的方式解释您的字符串文字,而不是转义反斜杠字符,包括空格。 这些被称为逐字字符串文字 。 您可以通过在字符串前加上@字符来实现此目的。 例如: @"C:\MyDirectory\MyFile.txt"

  3. 您现在使用的正斜杠字符的工作原因是出于向后兼容的原因。 它不是错误的原因(正如你可以从exception消息中看到的那样,包括被搜索的路径),但在路径中使用正斜杠可能仍然不是一个好主意。 如上所述,反斜杠是Windows中的标准路径分隔符。

我认为因为你的文件名中有一个“\”,它可能会弄乱它并告诉它查看attacks.txt文件的字符文件夹。

编辑:或者至少它看起来像你告诉它你的文件中有一个斜杠。 它在错误中为您提供的文件路径是您计算机上文件的实际位置吗?

是的如果你用’\’替换’/’你会得到一个无效的字符错误。 尝试使用2斜杠

 System.IO.StreamReader file = new System.IO.StreamReader("character\\attacks.txt"); 

要么

 System.IO.StreamReader file = new System.IO.StreamReader(@"character\attacks.txt"); 
  1. Posix路径分割器是/并且在Windows\
  2. 使用Directory.GetCurrentDirectory确保当前目录正确。
  3. 如果当前目录不正确,请使用完整路径或通过Directory.SetCurrentDirectory更改当前目录