C#找不到文件

And*_*rey 2 c# file-io visual-studio-2008

我有一个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()); 
            }
Run Code Online (Sandbox Code Playgroud)

异常错误:

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
Run Code Online (Sandbox Code Playgroud)

我正在从Python移植代码,对此从未遇到任何麻烦。提前致谢!

Cod*_*ray 5

真奇怪 计算机似乎坚信目录中没有attacks.txt文件D:\Users\Andrey\Desktop\Turn\character\,但是您说它确实存在。你们中的一个肯定是错的,多年来,我已经了解到计算机正确的使用率比我实际的高。

您确定文件实际上具有.txt扩展名,而不是.txt.somethingelse扩展名吗?如果在Windows Shell中关闭了文件扩展名的显示,则可能缺少此额外的文件扩展名。但是,计算机并没有在内部丢失它,并且将其视为与您请求的文件完全不同的文件。那家伙也有同样的问题。

重新配置Windows资源管理器:

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

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

  1. 确保如果在字符串文字中使用反斜杠(这是标准的Windows路径分隔符),则使用第二个反斜杠“转义”它们。之所以需要这样做,是因为C#编译器将反斜杠解释为转义字符,从而允许您键入诸如\t插入制表符之类的内容。如果要插入常规反斜杠,则必须转义转义符\\。这就是您尝试使用单个反斜杠时出现错误的原因。

  2. 不必转义反斜杠字符,您可以告诉C#编译器完全按照键入的字符串文字(包括空格)来解释它。这些称为逐字字符串文字。为此,您可以在字符串前面加上@字符。例如:@"C:\MyDirectory\MyFile.txt"

  3. 您现在使用的正斜杠字符现在起作用的原因严格是出于向后兼容的原因。这不是错误的原因(从异常消息中可以看到,其中包括正在搜索的路径),但是在路径中使用正斜杠可能仍然不是一个好主意。如前所述,反斜杠是Windows中的标准路径分隔符。