gpt4 book ai didi

C# 找不到文件

转载 作者:行者123 更新时间:2023-12-05 08:44:20 24 4
gpt4 key购买 nike

我有一个 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());
}

异常错误:

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 中关闭了文件扩展名的显示,您可能会丢失这个额外的文件扩展名。不过,计算机并没有在内部丢失它,而是将其视为与您请求的文件完全不同的文件。那是同样的问题this guy有。

重新配置 Windows 资源管理器:

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

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

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

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

  3. 您现在使用的正斜杠字符之所以有效,完全是出于向后兼容的原因。这不是错误的原因(正如您从异常消息中看到的那样,其中包括正在搜索的路径),但在路径中使用正斜杠可能仍然不是一个好主意。正如我上面提到的,反斜杠是 Windows 中的标准路径分隔符。

关于C# 找不到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11770928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com